Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Inside the MATLAB Desktop

April 14th, 2008

A Link to the Data

In Release 2008a, we added the ability to link plots to source data. With this feature, you tie a plot to a particular value in the workspace. When that value changes, the plot is automatically updated, with no further intervention on your part.

For this release, we’ve made a short video tutorial explaining how to use this feature, with a particularly useful application: watching your variables change during a debugging session. The second half of the video covers another new feature, data brushing, which is a topic for a later post.

One use not covered in the video is for observing real-time data. A while back I wrote a program to monitor incoming bytes from the serial port and update a graph with that data: a serial “oscilliscope”, if you will. In order to achieve smooth scrolling, instead of re-plotting the data, I modified the axes’ Xdata and Ydata properties whenever there were
BytesAvailable
. This was a cumbersome hack.

With this new feature, I can just use the data callback function to update my variable in the workspace and let the plot and linkdata objects do the heavy lifting.

The following real-time example uses the yahoo function from the Datafeed Toolbox. The same principles can be applied to any asynchronous callback in MATLAB, such as the above-mentioned BytesAvailableFcn for a serial object, most of the objects from the Data, Instrument, or Image Acquisition Toolboxes, Simulink and the target link toolboxes, or even a GUI control callback. This code uses a timer object to query AT&T’s stock price every 10 seconds, and adds that value to an array in the workspace.

Because the plot is linked to the data, the plot automatically updates to reflect the new value, thus giving us a real-time stock ticker.

close all;delete(timerfindall);clear all;
Connect = yahoo; %Datafeed Toolbox function
val=[];
time=[];
t = timer(‘TimerFcn’,
    [‘data = fetch(Connect, ”t”,”last”);’
    ‘val(end+1) = data.last;’
    ‘time(end+1)=rem(now,1);’] ,
    ‘Period’, 10,‘ExecutionMode’,‘fixedRate’);
start(t) %start the timer
%unambiguously set the source data
plot(time,val,‘XDataSource’,‘time’,‘YDataSource’,‘val’)
title(‘Price of AT&T’)
linkdata on %link the the data to the plot
AT&T stock price over a few minutes

Watching a stock fluctuate over a few minutes isn’t generally exciting, but you get the idea. What’s the big deal, then? I think this feature is best for when we don’t know when the data is going to change (but that it will), or when you want change the data iteratively and interactively without having to do a lot of retyping, as in the following example.

I like linking for situations where one is tinkering around with a variable in the command window. For me this is usually applying different filters to some data until I get the parameters just right. For instance, let’s say I have some data and I want to tweak filter coefficients until I get the desired response on my data. The following example requires the Signal Processing Toolbox.

First let’s set up the data:

t = linspace(0,6*pi,100);
x = sawtooth(t); %sawtooth wave - Signal Processing Toolbox function
y = x;
plot(abs(fft(y)))
Sawtooth frequency response

This time let’s use the GUI to set the YDataSource by clicking the link button: . Then, click the “fix it” link (1) in the message bar, and then enter a fft expression in the YDataSource field (2).

Linked plot GUI

Now let’s try out a 2nd-order butterworth filter. We won’t have to manually re-FFT or re-plot the new output:

[a,b]=butter(2,0.1); %Signal Processing Toolbox function
y = filter(a,b,x);
Linked plot after 2nd order butterworth

Close, but not quite, so I’ll try upping the order to 4:

[a,b] = butter(4,0.1);
y=filter(a,b,x)
Linked plot after 4th order butterworth

Good enough! Of course I could have just as easily put the whole filter expression in my YDataSource instead, saving me an extra line.

I invite you to let us know what other creative uses for this you come up with. Do I hear animation?

April 7th, 2008

The Tools You Want Where You Want Them

That title sounds like somebody’s advertising catch phrase, but what I’m referring to is the toolbar customization and rearrangement capability that was added to the MATLAB desktop in R2008a. This is, of course, nothing revolutionary, but it is new to MATLAB (I almost tripped on another catch phrase there). If you right-click (Command-click on Mac) on the main desktop toolbar or on either of the Editor toolbars, the context menu will offer a “Customize…” option. Selecting this option will display a Toolbar Preferences panel within the Preferences Dialog:

Toolbar Customization Panel

You can use this panel to specify which controls you want to appear on a toolbar and in what order. To add and remove controls simply check and uncheck the corresponding entries in the list that occupies most of the panel. As you check and uncheck controls, they appear and disappear from the layout area above. Within the layout area you can then rearrange the controls you have selected by dragging them.

For an example of what you might do with this capability here is my customized Editor toolbar:

My Customized Editor Toolbar

I always use the keyboard shortcuts for Cut, Copy and Paste so I removed those buttons. The buttons I use the most are the ones that control debugging so I moved them to the beginning. I moved Print and Publish to the end of the toolbar since I don’t happen to make much use of them. This way, if I make my editor narrow, my favorite buttons don’t drop off the end of the toolbar.

As for my main MATLAB toolbar and the Shortcuts toolbar I’ve configured them as follows:

My Customized Main Toolbar

I again removed Cut, Copy and Paste. Furthermore, I haven’t found much use for Undo and Redo outside the context of the Editor so they’re gone too. This shortened the main toolbar a bit. I took advantage of this extra space by dragging my Shortcuts toolbar to be adjacent to the main toolbar. I now have all the tools I want on a single row, leaving more working real-estate.

One reason I’m excited about the customization capability is that it allows us to offer a more extensive palette of toolbar controls in the future without cluttering everyone’s toolbar with all possible controls.

It dawned on me that my recent posts have discussed the Document Bar, Title Bars and now ToolBars. Maybe I should change my e-mail signature to

Peter Muellers
Desktop Bar Tender
The MathWorks, Inc.

March 31st, 2008

Help us help you

If you are a regular reader of this blog, you are probably already aware that we monitor your comments closely. In fact, we’re always looking for ways to get feedback from MATLAB users. Along with the great feedback we get through technical support and our user surveys, we’re continually checking the file exchange and the MATLAB Newsgroup for your ideas.

Our documentation group is just as interested in hearing from you as our developers are. Starting with R2007b, nearly every page in the Help browser includes links to a feedback form at the top

and bottom

of the page. The online documentation on our web site contains links to the same feedback form.

You can be as specific as you want about the page you’re commenting on - the form keeps track of which page you were viewing when you clicked on the feedback link. Or, if you couldn’t find what you were looking for, feel free to give us feedback about the page on which you expected to find a topic. Each request will be routed to the appropriate writer and taken into consideration for the documentation of the next release. If you include your email address in your feedback, you can expect to hear back from the writer with any comments or questions they might have, as well as a summary of any action they are taking as a result of your feedback.

So, if you couldn’t have done your job without our documentation, let the writer know. If you think you have an example that’s even better than the one we provide, we want to know about that too. We’ve already gotten lots of good feedback from you; nearly half of the comments we have received have directly resulted in improvements and corrections in our documentation. You’ve shown us that you can make our documentation better, and we want you to keep it up. Our documentation team looks forward to hearing from you!

March 24th, 2008

Publishing made easy with publish configurations

The publish function has been around since R14 and has proved useful for a number of things, to include demonstrating concepts, creating reports and generating blogs. In R2008a we’ve made it easier to fit publishing into your work flow, by introducing publish configurations, younger brother to run configurations (introduced in R2007b).

The most significant change is that you can now have multiple sets of publish options associated with a single file - previously there was a single set of global publish options. This added flexibility allows you to more easily publish different files with different options and even publish the same file with different options.

To get aquatinted with this new feature, let’s look at how our very own Loren of Loren on the Art of MATLAB uses publish configurations in her workflow.

Loren’s Workflow:

After composing the first draft of her entry in the MATLAB Editor, Loren likes to check the spelling and grammar of the file. The easiest way to do this, is to publish the document to Word format, and then open the published output in Word. It’s important to publish the document first, as this ensures that she’s viewing the same content that the reader will be seeing.

Once Loren is happy with the entry, it’s time to publish it to HTML. One of the restrictions when publishing her blog is the width of the images - too wide an image causes scroll bars and layout problems, so she likes to restrict image width to 500 pixels.

Here’s are the steps Loren follows in order to take advantage of this new feature:

Draft Phase - Publishing to Word

Step 1: Once the draft is ready for spelling and grammar checking, open the configuration editor by clicking the drop down arrow next to the publish button and select Edit Publish Configurations for [your_file.m]:

This automatically creates a publish configuration with the name of your file (’foo’ in the figure above). You can also specify input to the function you’re publishing, as I’ve done above.

Notice that there are two sets of Publish Settings that ship with MATLAB: Factory Default and User Default. Every new publish configuration you create, will use the User Default settings, which you can change if you’d like (see the doc for how to do this). But you can also create custom sets of settings. In the next two steps we’ll create a custom set of publish settings that we can use now and in the future each time we want to spell check and grammar check our work.

Step 2: Change the Output file format to doc:

Notice that a dot is shown next to the Output file format setting, indicating that our settings have deviated from the User Default settings.

Step 3: Now click Save As… in the configuration editor and type Word for the Settings name in the Save Publish Settings As dialog. When you’ve finished typing the name click Save:

This creates a new set of publish settings that will be used in the current publish configuration. These new settings will also be available to use in other publish configurations via the Publish Settings combo box:

Step 4: Click Publish in the configuration editor and review the document.

Blog Phase - Publishing to HTML:

OK…the spelling and grammar have been checked and we’re ready to upload the blog entry to the web. Next we’ll open up the configuration editor again, create a new publish configuration and create another set of reusable publish options for blog posts.

Step 5: Press the add button in the configuration editor and select Publish Configuration:

This creates a new publish configuration associated with your file, which is named ‘foo_2′ in the example above. This configuration uses the User Default publish settings, and because the default output format is html, we don’t have to change this setting.

Step 6: Now change the Max image width (pixels) to 500:

Finally, press Save As… in the configuration editor and type Blog for the Settings name and click Save (as we did above).

Step 7: Click Publish and upload to the web!

End State:

Loren’s MATLAB file now has two publish configurations, one using the Word publish settings, and one using the Blog publish settings. Each time Loren creates a blog entry, she can create a publish configuration for her MATLAB file and select the publish settings appropriate for her current task (spelling and grammar checking or getting ready to upload to the web).

MATLAB saves all the configurations for every file, as well as the publish settings that are used within the configuration. This makes it easy for Loren to consistently publish a file with the same settings.

Give Publish Configurations a Try!

Your work flow and ultimate product may be different from Loren’s, but the publish configurations can reap the same work flow benefits for you. Let us know how you use this feature!

March 17th, 2008

What’s on my TODO list?

Oftentimes in the course of coding, I find myself with little bits that I don’t want to deal with right away–things that I would like to come back to them later. Like most IDEs, MATLAB allows you to drop annotations which indicate things to do, fix, or otherwise note for later.

By adding a comment with the text: “TODO” or “FIXME” in a MATLAB file, you automatically sign up for this feature. You can then use the TODO/FIXME report to scan all the files in a given directory for these tags, which presents the results to you in the web browser.

You can get to this report using the directory reports-drop down in the Current Directory Browser:

TODO/FIXME report in Directory Reports drop-down

Clicking on the TODO/FIXME report button will cause MATLAB to scan all the files in the current directory, and display each line in the files that have one of the keywords. For example, in my directory I have two files with applicable markers:

TODO/FIXME report in Directory Reports drop-down

You’ll notice that the report also picked up a line with a “NOTE” in it. As an added bonus, we can find up to one additional comment tag, “NOTE” by default, but you can enter whatever regular expression you desire. To specify your own custom tag, replace the text in the text field that reads “NOTE” in the TODO/FIXME report web page (see above screen shot) with your own regular expression.

In general, I recommend using these comments as quick reminders for changes you really, really will work on in the near future. I’ve found such notes lose meaning when viewed by others or even yourself when revisiting the code after it is no longer fresh.

March 10th, 2008

New and Updated Desktop Features in R2008a

R2008a is here and there are a number of great new features in the desktop. I’m only going to give a brief introduction to each of these shiny new features, though in future entires, we’ll explore them in greater detail.

If you see something that’s particularly interesting, leave a comment. The more comments about a feature, the sooner we’ll blog about it!

Customizable Toolbars
The Desktop and Editor now allow you to customize their toolbars. You can change the order of toolbar elements, or remove things you rarely use.

Customizable toolbars will really help stream-line your workflow, as you can arrange your toolbars based on how you use MATLAB.

Publish Configurations
Publish Configuration’s allow you to specify options to be passed to the publish function when you press the publish button. Publish Configurations work very similarly to Run Configurations, in that they can be edited in the Configuration Editor and are associated with a particular file.

In previous releases, there was one set of preferences that applied whenever you pressed the publish button. Now, you can create multiple sets of options for a given file. For example, you can have a configuration that publishes to Word and another that publishes to HTML.

Code Folding
We’ve added a whole bunch more foldable constructs. Here’s the complete list of what you can now fold in the MATLAB Editor:

  • Block comments
  • Cells used for rapid code iteration and publishing
  • Class code
  • Class enumeration blocks
  • Class event blocks
  • Class method blocks
  • Class properties blocks
  • For and parfor blocks
  • Function and class help
  • Function code
  • If/else blocks
  • Switch/case blocks
  • Try/catch blocks
  • While blocks

Data Brushing and Linked Plots
Data brushing is a new feature that lets you manually select data on a plot. This tool really fosters manual interaction and exploration of your data.

Linked plots are graphs that respond to backing data changes. The underlying data and plot are tied together, so a change in one, causes a change in the other. This is useful if you have multiple plots representing the same data, as you need only update the data in a single place in order to update your plots.

Variable Editor (previously Array Editor)
The Variable Editor now provides enhanced editing of Structures and Objects.

Directory Comparisons
The File Comparisons tool has been enhanced to support directory comparisons. Its name has also unsurprisingly been changed to the File and Directory Comparisons tool.

March 3rd, 2008

Sharing Your M-Lint Settings

Writing robust, production quality MATLAB code is a whole lot easier when you use M-Lint. M-Lint inspects your code for problems and also recommends changes that will help improve the performance or maintainability of your code. M-Lint is analogous to the spelling and grammar checkers I so depend on, available in most word processors.

In order to really take advantage of M-Lint, I’ve found it useful to integrate it into the code review process. So when working on a team project, we use an agreed upon set of M-Lint settings, which are stored on a public drive. Then, each developer points their M-Lint analyzer to those settings, and codes against them.

Finally, when completing a code review, one of the exit requirements is that the MATLAB code must be in a “green” state (no errors, no warnings). We do allow warnings to be ignored using %#ok, though good justification must be provided.

Here’s how you can set up shared M-Lint settings:

The person setting up the shared settings should do the following

  1. Open the Preferences dialog by going to File -> Preferences… and select M-Lint (you should see the dialog below)
  2. Tweak the M-Lint settings as needed
  3. Press Save As…
  4. Navigate to a shared directory and press Save (alternatively you could check this file into source control)

Each team member should do the following

  1. Open the Preferences dialog by going to File -> Preferences… and select M-Lint
  2. Click on the Active Settings combo-box and select Browse…

  3. Navigate to your teams shared M-Lint settings, select that file and click Open
  4. Press Apply or OK for the settings to become active.

Many of us work on multiple teams, so I should point out that it’s very easy to switch between M-Lint settings. Go to Tools -> M-Lint and select the appropriate settings for the project your working on.

I think you’ll find this approach really makes you think about your warnings, and it will force you to justify any usages of %#ok.

By the way, there’s a new blogger in the family. Seth will be talking about Simulink over at his new blog, Seth On Simulink. This will be a great place for Simulink users to pick up tips and tricks, as well as share their experiences with the product.

February 25th, 2008

Interactive web pages in MATLAB, part 3

As promised in my last post, this week we will complete our GUI by placing a dynamically-generated MATLAB figure back into the web page.

To show this, we will build upon the last example from last week. In that example, the page generates a sine wave with its settings derived from the HTML form. Instead of displaying the plot in a separate figure window, we’ll create it and print it to a file, where it will then be loaded back into the web page.

This demo (right-click to save) will only work in MATLAB web browser on Windows (sorry, Ken).

Clicking on the “Plot the Sine Wave” button causes the following to happen:

  1. The sine and plot are set-up using the form’s options, as before.
  2. The plot is exported to a PNG-file on disk, using the print command.
  3. The latest version of the image on disk is shown in the page, by refreshing an HTML element.

In order for these actions to work smoothly, the code makes use of a few tricks:

  • In the JavaScript function that creates the plot, we added some figure manipulations to the issued MATLAB command. The following code:

    commandURI+=”f=figure;set(f,’Visible’,'off’,'units’,'pixels’,” +
    “‘Position’,[0 0 270 210],’PaperPositionMode’,'auto’);”;

    1. Creates a new figure and saves its handle.
    2. Sets the figure’s properties so that figure is invisible (and therefore not shown to the user).
  • This code is followed with the print command to export the figure to disk. The specified options set the file-type to PNG and the print resolution to be that of the screen.


    commandURI+=”print(’sinewave.png’,'-dpng’,sprintf(’-f%d’,f),’-r0′);”;

  • In the page, I’ve placed an HTML iframe to display the image. The iframe element allows me to refresh its content without having to reload the entire page, providing a smooth transition when the button is pressed.


    <iframe name=”image” id=”image” frameborder=0 marginwidth=0 marginheight=0 scrolling=no width=270 height=210 src=”">

    The important properties of this iframe are: the id, which lets us get to it later, and the empty src, which gives us a blank page on startup.

  • The final piece to this code is the last line of JavaScript in the drawSine() function. The purpose of the code below is to give MATLAB enough time to process the plot command and make sure the file is saved to disk before it is reloaded. Here we set a timer for 0.5 seconds, and at the timeout replace the image-file source in the iframe.


    setTimeout(”document.getElementById(’image’).src=’sinewave.png’;”,500);

That’s pretty much it. I hope you’ve enjoyed this 3-part series, and good luck creating HTML GUIs in MATLAB. Let us know what kinds of interesting and crazy web pages you can think of.

February 18th, 2008

Interactive web pages in MATLAB, part 2

Last time, I described how to use static hyperlinks to run MATLAB commands from the web browser (remember: this only works in MATLAB’s web browser). This time I will show you how to use JavaScript to assemble and execute matlab: commands.

How do we move beyond using explicit hyperlinks for issuing MATLAB commands? The hyperlink-click equivalent operation in JavaScript is setting the document.location property to the desired URL.

The following example uses the web page’s load event to trigger the execution of the surf command. When the page is loaded in MATLAB’s web browser, a figure window will be automatically created with the surface plot.

When you open this example file (right-click to save) in the MATLAB web browser, which includes the code below…

<html>
<head><title>Calling MATLAB from JavaScript 1</title><head>
<body onload=”document.location=’matlab:surf(peaks)’”></body></html>

You’ll see a blank browser window (there’s no real displayable content in the file), and then you’ll see a figure window popup:

One thing to notice in this example is that the JavaScript function in the HTML onload event is specified as a String, and the document URI is a separate string. The single quotes (’) are the way to specify a string within a double-quoted (”) string, and has nothing to do with MATLAB strings, in this example.

How do we now make the MATLAB command dynamic so the web page user can influence what happens? For starters, we can read in the value of a control and use that in the URI string.

The next example (right-click to save) uses HTML forms to present controls to a user. When the button is pressed, MATLAB will plot (in a figure window) a sine wave of the given amplitude and frequency and plot appearance.

MATLAB Web Browser with sine-wave demo

Pressing the “Plot the Sine Wave” button yields the following plot:

matlabfromjs2.html figure window output

In the header I’ve created the following script block:

<script type=”text/javascript”>
  function drawSine() {
    commandURI=”matlab:t=linspace(0,1,100);”;
    commandURI+=”plot(t,”;
    commandURI+=document.sine.amplitude.value;
    commandURI+=”*sin(t*2*pi*”;
    commandURI+=document.sine.frequency.value + “)”;
    commandURI+=”,’” + document.sine.color.value +
      document.sine.linestyle.value +
      document.sine.markerstyle.value + “‘”;
    commandURI+=”);”;
    document.location=commandURI;
  }
</script>

A few key points about this code include:

  1. The code that builds the matlab: URI and executes it as a separate JavaScript function drawSine() in the web page’s header.
  2. For readability I’ve broken up the command into several lines and used the += syntax for String concatenation.
  3. I used the direct naming syntax for accessing the data in the form elements. This syntax requires us to give an explicit name to each of our form and input elements.
  4. The JavaScript code does not check for valid data in the input boxes, and bad values will produce an error in the Command Window (which may not be obvious to a person working only looking in the web browser).

Inside the body’s form, there are two text inputs, three choice elements, and a button input. The following code creates the button:


<input type=”button” onclick=”drawSine()” value=”Plot the Sine Wave”>

This is the starting point for dynamically building the MATLAB command URI strings. I’ve shown you how to use an HTML form to gather input to pass to a MATLAB function. Let us know if you know of other interesting usages of HTML and MATLAB, or run into something tricky.

Next time I’ll complete the tutorial by placing the figure back into in the web page, creating a full GUI.

Check out the first part of this entry:

For general information on programming HTML forms, see:

For general information on programming in JavaScript, see:

February 11th, 2008

Interactive web pages in MATLAB, part 1

This is the first post in a 3 part series on creating web pages in the MATLAB web browser that can interact with the MATLAB workspace. We’ll explore the building blocks for creating a HTML GUI in MATLAB.

Last year Kristin posted how to use the matlab: protocol in the Command Window to create hyperlinks that run MATLAB commands. But did you know that you can use the same protocol in MATLAB’s web browser?

Open the web browser inside MATLAB using the web command. Then in the document location bar, type “matlab:why” and press enter. You’ll get a generated message in the command window, similar to the one below:

MATLAB Web Browser with matlab:why in location bar
down arrow
WHY command window output

There are a few things worth noticing about this procedure:

  1. You can use matlab: to “navigate” to a command the way http: navigates to a web page or ftp: navigates to a file server.
  2. This protocol only works inside MATLAB’s built-in web browser. Using Firefox, IE, or any other browser will generate an unknown protocol error.
  3. The browser does not navigate away from the current page. For instance, if you had a page open already in the browser and then typed matlab:why, the address in the location bar would change, but the web page would not.
  4. The executed commands do not show up in the Command Window or Command History (though the output shows up in the Command Window). You’ll have the output but no record of the commands that generated it.

Let’s look at how to create MATLAB GUI’s with HTML.

Just like you can associate MATLAB commands as callbacks for buttons in a GUI created by GUIDE, you can associate MATLAB commands as “callbacks” to hyperlinks in a web page.

A standard HTML link looks like this:
<a href=”http://www.matlabcentral.com”>Go To MATLAB Central</a>
A MATLAB command link looks like this:
<a href=”matlab:why”>Why?</a>
Clicking on this MATLAB command hyperlink will run the why function in the MATLAB workspace.

One good usage of MATLAB command links is providing a static list of commands, like a launchpad/portal page or a Choose Your Own Adventure of MATLAB code. For an example download and publishthe attached dvplots_hyperlink_demo.m file. The result is an HTML file with matlab: hyperlinks. This demo allows you to create and interact with a series of vector plots. Here is what the published demo looks like:

Clicking on the “quiver” link for instance, brings up the following plot:

Next time I’ll explain how to dynamically generate matlab: URIs using JavaScript. Until then, let us know if and how you have been using matlab: in web pages so far.


Inside the MATLAB Desktop is written by the MATLAB Interface teams.

Team picture
  • Etienne: Hello, Is it possible to change the background color of a particular cell?
  • Ken: No problem Mark…glad to help. Enjoy your font!
  • Mark Andrews: Ken, thanks for replying @3 and giving such clear instructions on how to get this to work.
  • Steve Eddins: Hi Ken, Every year or so I try to find a programming font that would really make me happy. A couple of...
  • Ken: @Jiro: Andale Mono looks nice! I especially like the rendering of the letter “g”.
  • Ken: Hi Mark, The issue your referring to (see the bug report here) was fixed in version 7.5 (R2007b). The problem...
  • Jiro: Ken, That’s a nice font. I use “Andale Mono” which has a similar look. I also like the clear...
  • Queffurust: This is my “cleanup” ; shortcut clc % clear Command Window close all hidden % deletes all...
  • Mark Andrews: Ken, should this work with version 7.0 (R14) on Windows? My favorite font is Consolas, but MATLAB seems...
  • Mark Feldman: Like Bryan (#38) and Kim (#40), I strongly request that you add native vi key bindings to the MATLAB...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.

Related Topics