Mike on the MATLAB Desktop

February 8th, 2010

Starting MATLAB from the OS X Dock

Once again, I’d like to welcome guest blogger Ken Atwell. Ken is a product manager for MATLAB who spends much of his time focusing on platform support. His past blog posts about the release of Snow Leopard and Windows 7 generated quite a bit of interest and discussion, so Ken will be occasionally blogging about platform considerations when using MATLAB. This week, Ken writes about the relationship between MATLAB and the Mac OS X Dock.

The Dock is OS X’s mechanism for giving users access to frequently-used applications. There are two primary ways to get an application into the Dock. However, in the case of MATLAB, only one of these will work:

  1. The Working Way. Go to your Applications folder and drag the MATLAB application (it will be called “MATLAB_R2009b.app” or similar, depending on the version of MATLAB you have installed) to the Dock (Figure 1). The icon will be the familiar L-shaped membrane, but with an up-arrow overlay.
  2. The Not Working Way. Start MATLAB from Applications, and then add MATLAB to the Dock using click-and-hold->Options->Keep in the Dock. Unfortunately, starting MATLAB from a Dock icon created this way will results in a MATLAB crash at start-up. If you have created a Dock icon in this manner, remove it and recreate it using the “working” method above.

Figure 1: Dragging the MATLAB app from Applications to the Dock
 Dragging the MATLAB app from Applications to the Dock

What is going on?! The reason for this behavior lies in MATLAB’s somewhat complex start-up sequence. MATLAB is started through a starter application that is responsible for starting the “real” MATLAB. In the first case, the starter application is added to the Dock (which is why the icon includes an up-arrow). In the second case, the “real” MATLAB is added to the Dock, and starting the “real” MATLAB directly from the Dock (or the Finder, for that matter) results in a crash. We expect to correct this in a future version of MATLAB.

With the starter application in the Dock, MATLAB should start normally and you will get a second MATLAB icon (the running, “real” MATLAB) in the Dock (Figure 2). Again, we acknowledge this is could be improved; there should only be one icon.

Figure 2: The Dock containing both the “real” MATLAB and the starter application
 Dragging the MATLAB app from Applications to the Dock

Once MATLAB is running, you can use either of these icons to bring MATLAB into focus. Given this behavior, it may be unclear how you can start a second instance of MATLAB. You can do this from a Terminal window as follows (replacing “R2009b” with your version of MATLAB as required):

  1. Go to the Utilities folder inside your Application folder.
  2. Open Terminal.
  3. Type: /Applications/MATLAB_R2009b.app/bin/matlab
  4. Press Return.
  5. Note that closing the terminal window will also close the second MATLAB.

Be aware that changing any application setting that is saved on disk, such as your Preferences, Desktop layout, and MATLAB path, will not take effect across other already-running instances of MATLAB, and the exact state that will be stored to disk can be difficult to predict. For this reason, I recommend against wholesale changes to your MATLAB environment when running multiple instances of MATLAB.

I hope this information will be helpful to Mac users who would like to launch MATLAB directly from the Dock. If you have any other Dock tricks you’d like to share with fellow MATLAB users, please chime in below!

February 1st, 2010

Speeding up your program through Profiling

I was originally going to write about about a minor feature of the MATLAB Profiler, but while skimming through the archives here, I realize we haven’t really talked much about profiling at all! So it’s time to go back to MATLAB basics and talk about Profiling.

The Profiler is one of several dynamic analysis tools. The most common form of dynamic analysis focuses on correctness. In that workflow, you run your code and check whether the calculated result matches the expected result. If it doesn’t match you either made some bad assumptions about your data or there’s a bug in the program. You can use tools like the MATLAB Debugger and M-Lint to figure out the problem. A less common way to analyze code is to look at efficiency, in this case how long it takes to run (we’ll look in to memory another time). The Profiler lets you run a program and then look at how long each line took to execute. With this information you can concentrate on optimizing the sections of code that take up the most time.

By default the Profler is not visible on the Desktop. To get it, use the Desktop menu, under Desktop -> Profiler. This brings up the Profiler window (it looks like the Web browser).

Open the MATLAB Profiler with Destkop - Profile
MATLAB Profiler

In the Profiler’s toolbar enter the MATLAB command(s) you wish to profile (where the URL would go if it were a web browser). You can combine multiple MATLAB statements with a “,” or “;”. This way you can set up inputs, if necessary. For example: A = rand(10); myfun(A). Once you enter the function(s) to profile, press Enter to run them. My example uses following function awhile.m:

function z = awhile
    for i=100:100:300
        x = rand(i);
        y = rand(i);
        z = calculate(x,y);
    end
function z = calculate(x,y)
    z = conv2(x,y);
    pause(2);

From the results below, we can see that running awhile took 16 seconds on my computer (the time is listed next to the black bullet on the toolbar). Of that 16 seconds 14.823 was spent in that one function, with almost 100% of that time spent in the three calls to the calculate subfunction. This result is not surprising given my example code. Note that 14.823 < 16. What happened to the other 1.177 seconds? The “16 seconds” reflects the total real time spent from the time the Profiler was started to when it was told to stop, rounded to the nearest second. The reported 14.823 seconds is the amount of time spent by the CPU running that code, and does not reflect the overhead of the operating system or any commands issued around the profiled function.

MATLAB Profiler results from awhile.m

Clicking on a listed function or subfunction will take you to a page that lists a lot detail about each line of code in that function, including:

  • Which functions called that the function and how many times
  • The individual lines where the most time was spent, including the number of times that line was executed and how much time was spent on that line
  • What other profiled functions were called by that function
  • Any warnings reported by M-lint, which can provide suggestions for improving performance
  • A coverage summary showing the number of lines run vs not run
  • A color-coded version of your code, showing potential problem spots.

In the picture below we see that 8.85 seconds of the time was spent in conv2 and 5.97 seconds in pause. With the information presented in the report I know I can get a 40% speedup by eliminating the call to pause, but we see that the conv2 line is darker, meaning I’d get more bang for my buck by improving that line. Since this code doesn’t do anything useful, there’s nothing really to replace it with it. But in your own code you might see a way to either replace a dark red line, or call it fewer times.

The subfunction lines by time

To sumamrize, the workflow for profiling is:

  1. Find a program you wish to speed up.
  2. Run that code with appropriate inputs in the Profiler.
  3. Fix any performance-related M-Lint warnings in your file (if you haven’t already). The Profiler can help you asses which warnings are most significant.
  4. Look for the lines where the code spent the most time, and try to call that line fewer times, replace it with faster statements, or break your code into smaller problems.
  5. Repeat until there’s nothing left to improve.

The profiler can also be run from the MATLAB command line using the profile command.

EDIT (02/01/10): Fixed typo.

January 25th, 2010

Open as Text

I bet good odds that most of our users don’t know about the “Open As Text” feature in the Current Folder Browser. Double-clicking on files in the Current Folder will try to open the file using MATLAB’s implementation of the open function. That means importing to the workspace for a data file, loading of a mdl-file in Simulink, and editing a regular “.m’ file in the Editor. Sometimes we may not want to open the file in the default way, but instead want to look at or edit the file as if it were a plain text file.

Let’s say I wanted to compare the years the Yankees and Red Sox won the World Series. To do this, I’ll have my friend over in the facts department sent me a tab-delimited file with the years each team won the World Series, “ws.dat”. Double-clicking it in the Current Folder Browser does the same operation as the MATLAB command open(’ws.dat’), that is, the Import Wizard is launched and the data can be imported into the workspace.

Double-click to import

With this imported data, we can quickly visualize the years that each team won the World Series (I’ll leave it as an exercise for the the reader to interpret the results).

cla
hold on
bar(data(:,2),repmat(1,1,27),‘r’)
bar(data(:,1),repmat(1,1,27),‘b’)
set(gca,‘YTickLabel’,[])
set(gca,‘YTick’,[])
set(gca,‘YLim’,[0 1.1])
legend({colheaders{2:-1:1}})
Original plot of yankees vs red sox

Looking over the data, I notice that my friend has made a mistake by sending me an older version of the file that does not have the Yankees’ most recent win. Rather than send him an email and wait an indeterminate amount of time for the new file, I’ll just go ahead and edit the file locally. Obviously, we can’t edit the file by double clicking since that brings up the Import Wizard, instead, let’s right-click and select open as text.

open as text on context menu

This opens the file in the Editor, now we can quickly add 2009 to the bottom of the list, save and replot. Voila!

Fixed plot of yankees vs red sox

EDIT (25-01-2010): fixed typo in open command example

January 18th, 2010

Two editor shortcuts I bet you didn’t know about

The MATLAB Editor has plenty of handy text-editing actions built in to it. Unfortunately we don’t have a concise way of advertising or providing default keyboard shortcuts for all them. Amongst the standard cut/copy/paste-style actions that we are all familiar with, the Editor also has two forward-deleting actions.

The first is “Remove Next Word” (Ctrl+Delete default on Windows). This does almost exactly what you’d think. Starting at the caret (or, text insertion point) all text up to the next letter after a space is deleted. So if you’re at the end of the word, the space is deleted. If you’re in the middle of a word the rest of the word and following space is deleted. Basically, this sticks the next word to the right of where you are. Used in the standard way, repeated invocations go through your line (and on to the next) deleting one word at a time. This is useful when you find yourself holding down the shift and ctrl key with the right arrow to select a bunch a text for the purpose of deleting it.

The other action is “Kill Line” (Ctrl+K default on Windows). This action deletes from the caret forward to the end of a line. A second Ctrl+K deletes the newline character bringing the next line up. This single action replaces the Shift+End, Delete combo. By default this action is only bound to Ctrl+K in the Command Window. To get it in the Editor, (1) go to File -> Preferences -> Keyboard -> Shortcuts, (2) search for “Kill Line”, (3) select the shortcut and in the table below, (4) click the drop-down arrow and check the “MATLAB Editor” checkbox.

Enabling the kill-line action in the Keyboard Preferences

While you’re in the Keyboard Shortcut preferences, you can browse the list to see the tons of other editing commands that are available.

January 11th, 2010

The Preferences folder: matlab.prf

Continuing my discussion on the MATLAB Preferences folder, today’s article is about one particular file in that folder. (Remember you can find the folder location with the prefdir command). That file is matlab.prf, which stores the changes you’ve made to your preferences from the Preferences panel. This file is just a simple list of the various preferences altered from their default with their new value, encoded in a way that makes sense to our preferences code. Even though it’s ASCII, the file is not meant to be human readable, but if you look closely, I’m sure you can figure it out.

Between releases, you shouldn’t rely on the continued existence of any particular key or value type, as we often change these from release to release. Knowing about this file is useful when manually managing different preference sets or manually upgrading. For example, since you can’t have multiple preference directories, you can set up one session of MATLAB how you like it, copy the matlab.prf file to safe location, and repeat for as many configurations as you wish. To switch between them, you have to manually copy the saved .prf file back into your preferences directory. Obviously this is annoying and does not work well if you have to switch often. This workflow is more useful for sharing preferences; that is, copying the file from one user’s prefdir to another’s. (Note since the prf file contains paths to other files those files may not exist on the new user’s computer, or may be incompatible with their system).

If you skip a release or two and don’t get your preferences automatically carried up, you can try copying the matlab.prf from the old preferences folder to the new one. I can’t guarantee that will work or won’t prevent MATLAB from starting properly, so please back up the original one first. Deleting the file or replacing it with a working backup will fix any issue caused by copying a different prf file.

MATLAB caches the preference values once it reads the prf-file; if you manually modify this file, you’ll have to restart MATLAB to see the effects.

My R2009a matlab.prf file
A matlab.prf file

January 4th, 2010

The new New Year’s Resolutions

Like I did in 2009, I’m making some New Year’s resolutions for 2010. Once again I hope to have a productive year. We have some really useful stuff planned for R2010a and R2010b and hopefully your daily work will be easier.

My New Year's Resolution is to continue providing useful articles about desktop features, bring in insightful guest posters, and broaden the scope to cover more of the desktop.

December 28th, 2009

2009 Blog Retrospective

Now that 2009 is almost at a close, I thought I’d share my retrospective. Based on the number of comments and hits to our web pages, the most popular topics this year were platform issues and news, Emacs, and GUIs. It’s no surprise that the best received and viewed posts pertained to the MATLAB Editor, since Ken and I both worked primarily on the Editor during the past year. Your feedback has been great and learning about what interests our audience helps us decide what to write about. Our three most popular posts of 2009, in terms of comments:

  1. Pouncing on Snow Leopard
  2. It’s the Little Things That Count
  3. Tab to Narrow Completions

We’ve heard you loud and clear about platform fidelity and competitiveness with other Editors. I think we made great strides in those areas in 2009, and have wonderful things planned for 2010.

I also learned that free t-shirts are not a good motivator for getting responses. I think next time I’ll try free copies of Emacs or chocolate peanut butter.

The big surprise for me is the rate at which new comments continue to come in our uitable post. Well that, and ending up the owner of this blog barely a year after Ken and I officially took it over. Next year I plan on having the same set of regular guest posters as well as some new faces to help out with the articles.

At the beginning of the year, Ken and I made some new year’s resolutions. I am going to give Ken a check-plus on his resolution. He nailed it with the new search field, the more Mac-like tabs, and getting guest posts regularly on Windows and Macintosh. I’m going to give myself a check. Overall I think I made improvements in our code base, but although I did slim down a number of widgets, we added a lot of features so the code footprint did increase in our area. As for useful tips and tricks, I think I did well covering using java, organizing files, and Gui internationalization.

Have a good New Year’s and a happy and healthy 2010.

December 21st, 2009

R2009 in review

We’ve had a fantastic year with new and improved features in MATLAB R2009a and R2009b. Let’s take a walk down memory lane…

On the MATLAB desktop
2009 was a big year for our power users. R2009b introduced customizeable keyboard shortcuts. Many actions from simple open, new, cut, and copy to more complex ones such as inserting publish formatting or launching reports are now available for you to bind to any key combinations you wish. Many of you have requested this feature over the years, and we are quite happy to deliver it. This feature allows saving and sharing of custom keybinding sets and we hope you’ll share good ones with us here on the blog and on the file exchange….

…which you can get to with the brand new in File Exchange application that allows you to search user-contributed files and download them for use in your MATLAB programs. The program doesn’t yet let you upload directly from MATLAB, but don’t let that stop you from contributing your own files through the web interface. Those files let us and MATLAB users around the world learn from how you use MATLAB and allow your colleagues to do new and interesting things, all for the low sum of zero dollars.

The current folder saw a redesign with a new address bar, a tree view expandable folders, a search bar, and a preview pane for viewing the contents of files without opening them. While not easy to enumerate, we feel this new interface significantly enhances a number of workflows and makes it easier to manage projects that span multiple folders on disk.

Also updated this year was the plot selector. The new plot selector makes it easier to find the most useful plot types as well as see plots provided by the various toolboxes you have installed.

Static Analysis in the Editor

We introduced Extended M-Lint tips in ‘9a. This feature allows you to request on-demand help for many warning, error, and informational messages about your code. If the short information is enough for you deal with it, great. If not, you’ve got a mechanism to request more information. Most of the long messages have links to open the documentation for yet even more information. This progressive disclosure allows us to be helpful without being annoying.

At the same time we made easier to configure which messages are show in the editor through a new preferences interface with search capability. These enhancements have laid the foundation for us to provide additional forms of code analysis in the future.

Publishing
Both 2009 releases had improvements to our code publishing feature. First we introduced new figure capturing modes to allow you better control on how figures and GUIs are placed into a published document. Then came the ability to publish directly to PDF. PDF files aren’t as easy to read on as many devices as html, but easy to share since both the text and figures are in the same file.

 

 

Help
2009 was also a big year for the help browser. Introduced was a new short-width layout, searching with improved search results and better organization of those results. Also added was a breadcrumb/navigational bar to the help so you can move about the help without having to constantly swap between contents and search views.

 

 

Platform Support
Two major operating systems were released in 2009: Mac OS X 10.6 Snow Leopard and Windows 7. MATLAB R2009b runs on both platforms, although as some of you have noticed there has been a few sporadic issues with the interface on Snow Leopard. We’re aware of them and we’re working internally and with our vendors to resolve or work around those issues. We’ve also enhanced the look and feel of some of our components to appear more like the standard widgets. Such as Ken’s more Mac-like tabs.

Release Notes
The following release notes describe the new desktop functionality in each release.

How has MATLAB made your life better in 2009?

December 14th, 2009

Using Run Configurations for Debugging

Astute readers may notice that this blog has once again changed name. Ken has moved out to California to work for Apple and we wish him the best of luck there. In his honor, I'm going to highlight another clever way of using Run Configurations. Earlier this year Ken posted about using the Run Configurations to profile a file, and now I'm going to describe how to use Run Configurations for debugging.

I've put together a toy example below that combines two elements that I find useful for debugging with run configurations. With these you can have a "run in debug" mode configuration and a "run regular" configuration.

  1. Use a debug flag.You can add an additional boolean parameter to your function to switch behavior or print out informational messages to a file or the Command Window. Use an integer if you want to have different levels of logging. In my example when the debug flag is set, my code prints information with disp to the Command Window and runs a potentially dangerous subfunction without a try/catch.
  2. Use dbstop. Add breakpoints or break conditions (such as "if error" or "if caught error")
  3. before running the file. This allows you have to a consistent and controllable debug environment for the file. It's useful if you're like me and constantly clear your breakpoints accidentally with a clear all, or don't want to be in a dbstop if error situation during your whole MATLAB session.

You can see here I have two configurations for this file: "broken" (the name of the function) and "debug" which from the tooltip you can see is my debug configuration.

broken.m with debug and regular run configurations

Here the configurations in detail:

1. regular configuration

%turn off the debug flag

flag = false;

broken(flag);

2. debug configuration

%save break points
s = dbstatus;

%set a debug flag
flag=true;
dbstop if error

%run the function
broken(flag)

%restore breakpoints
dbstop(s)

December 7th, 2009

The Preferences Directory

There are lots of ways a computer program can store user settings. In MATLAB we use a series of different files in a special per-release directory that is in a standard platform-specific place on your disk. In Windows it's usually under the Profiles\user\Application Data directory and on linux under /home/user/. To find out what the directory any given install of MATLAB uses, use the prefdir function:

prefdir
ans =

C:\WINNT\Profiles\mkatz\Application Data\MathWorks\MATLAB\R2009b

As the directory name indicates, MATLAB creates a separate directory for each release you have installed. When you install MATLAB it looks to see if you have a preferences directory already for that release, if not it goes the latest release you have and copies over the applicable preferences to the new release. Normally this works fine, but in rare cases the installation messes up and you can get your preferences into a weird state. When that kind of thing happens you can just rename the old dir temporarily and try again.

Deleting (or renaming) the preference directory for any given release after it is installed is a big hammer that resets your preferences to the most recent release you have preferences for.

  1. Close MATLAB, after making a note of the prefdir location.
  2. Go to one level above that directory and rename it, e.g. R2009b_OLD
  3. Restart MATLAB

When MATLAB starts and there is no directory for that release, MATLAB will regenerate the preferences directory with default values for everything.

If you don't like the default location for the preferences directory, you can manually specify its location using an environment variable. Instructions to do this are given in this solution.

Finally, the various parts of the preferences are stored in different files in this directory. You can manually, at your own risk, handle upgrading from one release to another. For example you can try migrating shortcuts but not key bindings. Doing this is dangerous though, as we frequently change functionality or how the data is represented on disk. In future posts, I'll highlight some of the more useful preference files.


Mike works on the MATLAB Desktop team.
  • Hooman Javidnia: This might not be directly relevant to the topic of the blog, but since we are talking about running...
  • Joe M.: Your description of the dock workaround includes Terminal commands, because Finder can’t see past...
  • Mike: @Chris, Thanks for the feedback. We made this post because we are aware of the limitations and pains, and we...
  • Chris: Issues like this may seem like small things, but in my opinion they keep Matlab from being a first-class...
  • Mike: @Amin, com.mathworks.* represent Java classes that we’ve built here. These mostly represent the libraries...
  • Mike: @OysterEngineer, I think the community here is pretty supportive. Your comments are always appreciated. Given...
  • Amin: Hi Mike what is the com.mathworks package? where i can read more about objects and classes of this package?
  • James Holland Jones: I’ve tried to add some emacs key bindings in the Keyboard Shortcuts Preferences pane and...
  • James Holland Jones: Flash forward to R2009b. What if you’re a Mac user and you actually *want* emacs key...
  • us: mike, nice blog however, you should also mention these two commands, which we put into our startup.m files…...

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