Mike on the MATLAB Desktop

December 19th, 2011

MATLAB Startup Accelerator

Another new feature of MATLAB R2011b is the Startup Accelerator, which improves MATLAB startup time on Windows by caching important files that MATLAB needs to properly launch. This is done through a scheduled task that runs periodically to update the cache. In a normal installation of MATLAB, there is nothing you need to do to get this benefit. Hopefully by now you’ve noticed R2011b loads faster than previous releases.

In case you’re curious, you can read this solution http://www.mathworks.com/support/solutions/en/data/1-FBGXHZ/index.html?solution=1-FBGXHZ. It explains how the Windows Task Scheduler is used and how to install the Startup Accelerator on a network installation of MATLAB.

November 28th, 2011

Using Dates in MATLAB

Three weeks ago I wrote about MATLAB's new spreadsheet import tool. Since then I've had a few conversations regarding using dates in MATLAB; dates are common as column headers or table data. The import tool will turn Excel dates into MATLAB datenums. A datenum in MATLAB is just a double that represents any date & time after midnight Jan 1, 0000 AD. MATLAB comes with several useful functions for handling these special case numbers, and in particular for displaying them.

The now, clock, and date functions will provide the current date & time as a datenum, datevec, or detestr, respectively. While a datenum is a single number representing the date and time, a datevec splits the year, month, day, hour, minute, and second components out in 1x6 vector. A datestr is the string representation of a date time. There are a ton formatting options available for how the date and time are displayed (see below).

currentTimeAndDate = now
currentTimeAndDateAsVector = clock
currentDateAsString = date
currentTimeAndDate =

   7.3484e+05

currentTimeAndDateAsVector =

         2011           11           28            8           50       20.486

currentDateAsString =

28-Nov-2011

As far as the data is concerned, these three date types are interchangeable using the conversion functions. You can use the datenum, datevec, and datestr functions to convert between the three types. Individual functions that perform calculations on dates usually prefer a particular format, for example addtodate looks for datenum types.

currentDateAsNumber = datenum(currentDateAsString)
currentDateAndDtimeAsNumber = datenum(currentTimeAndDate) %note the difference from above
currentDate = datestr(currentTimeAndDate)
currentDateAsVector = datevec(currentDateAsString)
currentDateAsNumber =

      734835

currentDateAndDtimeAsNumber =

   7.3484e+05

currentDate =

28-Nov-2011 08:50:20

currentDateAsVector =

        2011          11          28           0           0           0

The usage of dates I'm particularly interested in is with plots. Let's say we have some time-varying data and we want the x-axis to reflect those dates. If I just plot the data against the datenum, by default the x-labels will all be large, ugly numbers.

firstInMonths = repmat([2011 1 1 0 0 0],12,1);
firstInMonths(:,2) = 1:12;
bar(datenum(firstInMonths),rand(1,12)*10)
Random Date Data

Thankfully, MATLAB comes with a simple function, datetick, for turning those numbers into strings:

datetick
Random Date Data With Ticks

Unfortunately, those tick labels aren't very pretty. Let's use a date format with the datetick function to specify how we want labels to look. For this function, we can use any date format recognized by the detestr function (see below).

datetick('x','mmm-yy')
Random Date Data with well-formatted ticks

Finally, for your reference, here is the help information for datestr, which lists how to formate a date string:

help datestr
 DATESTR String representation of date.
    S = DATESTR(V) converts one or more date vectors V to date strings S.
    Input V must be an M-by-6 matrix containing M full (six-element) date
    vectors. Each element of V must be a positive double-precision number.
    DATESTR returns a column vector of M date strings, where M is the total
    number of date vectors in V. 

    S = DATESTR(N) converts one or more serial date numbers N to date
    strings S. Input argument N can be a scalar, vector, or
    multidimensional array of positive double-precision numbers. DATESTR
    returns a column vector of M date strings, where M is the total number
    of date numbers in N. 

    S = DATESTR(D, F) converts one or more date vectors, serial date
    numbers, or date strings D into the same number of date strings S.
    Input argument F is a format number or string that determines the
    format of the date string output. Valid values for F are given in Table
    1, below. Input F may also contain a free-form date format string
    consisting of format tokens as shown in Table 2, below. 

    Date strings with 2-character years are interpreted to be within the
    100 years centered around the current year. 

    S = DATESTR(S1, F, P) converts date string S1 to date string S,
    applying format F to the output string, and using pivot year P as the
    starting year of the 100-year range in which a two-character year
    resides. The default pivot year is the current year minus 50 years.
    F = -1 uses the default format.

 	S = DATESTR(...,'local') returns the string in a localized format. The
 	default (which can be called with 'en_US') is US English. This argument
 	must come last in the argument sequence.

 	Note:  The vectorized calling syntax can offer significant performance
 	improvement for large arrays.

 	Table 1: Standard MATLAB Date format definitions

    Number           String                   Example
    ===========================================================================
       0             'dd-mmm-yyyy HH:MM:SS'   01-Mar-2000 15:45:17
       1             'dd-mmm-yyyy'            01-Mar-2000
       2             'mm/dd/yy'               03/01/00
       3             'mmm'                    Mar
       4             'm'                      M
       5             'mm'                     03
       6             'mm/dd'                  03/01
       7             'dd'                     01
       8             'ddd'                    Wed
       9             'd'                      W
      10             'yyyy'                   2000
      11             'yy'                     00
      12             'mmmyy'                  Mar00
      13             'HH:MM:SS'               15:45:17
      14             'HH:MM:SS PM'             3:45:17 PM
      15             'HH:MM'                  15:45
      16             'HH:MM PM'                3:45 PM
      17             'QQ-YY'                  Q1-96
      18             'QQ'                     Q1
      19             'dd/mm'                  01/03
      20             'dd/mm/yy'               01/03/00
      21             'mmm.dd,yyyy HH:MM:SS'   Mar.01,2000 15:45:17
      22             'mmm.dd,yyyy'            Mar.01,2000
      23             'mm/dd/yyyy'             03/01/2000
      24             'dd/mm/yyyy'             01/03/2000
      25             'yy/mm/dd'               00/03/01
      26             'yyyy/mm/dd'             2000/03/01
      27             'QQ-YYYY'                Q1-1996
      28             'mmmyyyy'                Mar2000
      29 (ISO 8601)  'yyyy-mm-dd'             2000-03-01
      30 (ISO 8601)  'yyyymmddTHHMMSS'        20000301T154517
      31             'yyyy-mm-dd HH:MM:SS'    2000-03-01 15:45:17 

    Table 2: Free-form date format symbols

    Symbol  Interpretation of format symbol
    ===========================================================================
    yyyy    full year, e.g. 1990, 2000, 2002
    yy      partial year, e.g. 90, 00, 02
    mmmm    full name of the month, according to the calendar locale, e.g.
            "March", "April" in the UK and USA English locales.
    mmm     first three letters of the month, according to the calendar
            locale, e.g. "Mar", "Apr" in the UK and USA English locales.
    mm      numeric month of year, padded with leading zeros, e.g. ../03/..
            or ../12/..
    m       capitalized first letter of the month, according to the
            calendar locale; for backwards compatibility.
    dddd    full name of the weekday, according to the calendar locale, e.g.
            "Monday", "Tuesday", for the UK and USA calendar locales.
    ddd     first three letters of the weekday, according to the calendar
            locale, e.g. "Mon", "Tue", for the UK and USA calendar locales.
    dd      numeric day of the month, padded with leading zeros, e.g.
            05/../.. or 20/../..
    d       capitalized first letter of the weekday; for backwards
            compatibility
    HH      hour of the day, according to the time format. In case the time
            format AM | PM is set, HH does not pad with leading zeros. In
            case AM | PM is not set, display the hour of the day, padded
            with leading zeros. e.g 10:20 PM, which is equivalent to 22:20;
            9:00 AM, which is equivalent to 09:00.
    MM      minutes of the hour, padded with leading zeros, e.g. 10:15,
            10:05, 10:05 AM.
    SS      second of the minute, padded with leading zeros, e.g. 10:15:30,
            10:05:30, 10:05:30 AM.
    FFF     milliseconds field, padded with leading zeros, e.g.
            10:15:30.015.
    PM      set the time format as time of morning or time of afternoon. AM
            or PM is appended to the date string, as appropriate. 

    Examples:
 	DATESTR(now) returns '24-Jan-2003 11:58:15' for that particular date,
 	on an US English locale DATESTR(now,2) returns 01/24/03, the same as
 	for DATESTR(now,'mm/dd/yy') DATESTR(now,'dd.mm.yyyy') returns
 	24.01.2003 To convert a non-standard date form into a standard MATLAB
 	dateform, first convert the non-standard date form to a date number,
 	using DATENUM, for example,
 	DATESTR(DATENUM('24.01.2003','dd.mm.yyyy'),2) returns 01/24/03.

 	See also DATE, DATENUM, DATEVEC, DATETICK.

    Reference page in Help browser
       doc datestr

If you're interested in using dates with MATLAB, here is a link to the date functions that are available.

November 21st, 2011

4 Uses of MATLAB Mobile This Thanksgiving

1. Chef Aide
When cooking a large meal, I often need to make quick calculations and substitutions. For instance, how to handle measuring when all my tablespoons are in the sink? After pre-loading the Units Conversion Toolbox from the file exchange into MATLAB, I can figure out a workaround lickety-split:

MATLAB Mobile convert units with file exchange

Sure there are plenty of apps that will do this easier and out of the box, but that’s not as much fun as using MATLAB.

2. Black Friday Deal Calculator
How do you know how much are you going to save on a deal? In addition to all the powerful linear algebra built into MATLAB, it can also function as basic calculator. You can use MATLAB Mobile to calculate final prices, how much it will cost to drive across town to save an additional $10 on the same item, etc.

MATLAB Mobile to calculate the best squares in a football pool

3. Winning the football pool
With a little matrix manipulation and pre-computed probabilities, we can find out which boxes in a standard football pool have the best odds of winning. This is for the kind where you choose a square representing the last digit of the two teams’ scores. Thanks to the data from http://www.sabernomics.com/sabernomics/index.php/2005/01/squares-for-squares/, we can figure which square has the best odds:

MATLAB Mobile to calculate savings

Here’s the code if you want to cut & paste. Special thanks to Ned Gulley for inspiring this one.

prob = [1.7100 1.4800 0.5600 3.2100 2.0400 0.7200 1.5400 3.8000 0.9500 0.7400; ...
 1.4800 0.8500 0.3300 1.0000 2.2300 0.2400 0.9500 1.9300 1.3500 0.5600;...
 0.5600 0.3300 0.0400 0.5400 0.6500 0.3300 0.3500 0.4600 0.2200 0.3200;...
 3.2100 1.0000 0.5400 1.1900 1.4500 0.5200 1.6300 1.9300 0.6100 0.7200;...
 2.0400 2.2300 0.6500 1.4500 1.5900 0.5000 0.8200 3.7100 0.7200 0.6700;...
 0.7200 0.2400 0.3300 0.5200 0.5000 0.1900 0.2200 0.7600 0.6900 0.2400;...
 1.5400 0.9500 0.3500 1.6300 0.8200 0.2200 0.5600 0.8900 0.4800 0.6900;...
 3.8000 1.9300 0.4600 1.9300 3.7100 0.7600 0.8900 1.9300 0.8300 0.8000;...
 0.9500 1.3500 0.2200 0.6100 0.7200 0.6900 0.4800 0.8300 0.4100 0.3000;...
 0.7400 0.5600 0.3200 0.7200 0.6700 0.2400 0.6900 0.8000 0.3000 0.1900];

[~,IX] = sort(prob(:),'descend');
[row,col]=ind2sub(size(prob),IX);
bestscores = horzcat(row-1,col-1)
MATLAB Mobile to calculate savings

4. A Reason To Be Thankful
Some families’ tradition includes everyone stating a reason to be thankful. In addition to a thoughtful and inspired answer, why not throw out a joke one as well. The why function is always good for coming up with an answer on the spot.

MATLAB Mobile:why

Have a safe and happy Thanksgiving.

November 7th, 2011

The New Spreadsheet Import Tool

One of the most exciting new features in MATLAB R2011b is the Spreadsheet Import Tool. This tool makes it easy to import data from Microsoft Excel and comma-separated value (CSV) files. The spreadsheet import tool allows you to preview the file and then select the range and format of the data to import. To get started it’s as easy as double-clicking the any .csv or .xls file in the Folder Browser.

For this example, I went to data.gov to get a random CSV file. It’s an awesome place for getting sample data sets or to answer burning questions like “how much Sorghum did the US import in the 70′s?”

Here’s what the new tool looks like when I use it to import a CSV file:

Importing a spreadsheet

By default the tool wants to import the data as a matrix, using zeroes to fill in gaps. By using the toolbar, you can quickly customize this process. The first drop-down lets you choose between matrix, column vector, or cell array for the data type. The matrix and cell options will import into one variable, and the column vector will create a variable for each selected column. The variables can be quickly renamed by typing in the trapezoidal area at the top of the selection.

Importing a spreadsheet

This tool is highly interactive. You can quickly choose a subrange using all the normal multi-select gestures (e.g. shift & control click) for your platform. The selections don’t have to be contiguous, but each column has to have the same rows selected, which the tool enforces when you drag around a selection. You can also select a whole row or column by click on its respective header.

Importing a spreadsheet

You also have several options for deciding how to treat blank or non-numeric data. You can set up rules to have rows or columns containing such data automatically excluded, or to have that data replaced by a number, Inf, or NaN. When you do this, those cells are a highlighted in different colors with the new values super-imposed over the original. This allows you to quickly scan the data to make sure you get the desired results.

Finally you can import immediately into the workspace or generate a script or function that would allow you to process other files in the same manner. This is particularly useful if you work with multiple data sets generated in the same fashion.

For a more dynamic look at how to use this tool, watch the short video.

October 31st, 2011

Celebrating Our Community Milestones

I was just looking at a few things at MATLAB Central. It struck me that some really interesting things are going on that I wanted to share.

MATLAB Answers

Most of you probably remember that MATLAB Answers was launched in January. Since launch, we have had over 17,500 questions asked, over 13,000 answers made, and over 38,000 community members participated by asking questions, offering answers or comments to questions! It’s been really amazing watching all the activity that has been going on since the begining of this year. It is the contributions by each of our community members that makes MATLAB Answers, and MATLAB Central for that matter, such a great success.

Image

Eight members of our community have become MATLAB Answers Editors, by achieving a reputation of 1500. In addition to participating by answering your MATLAB questions, our editors also help make MATLAB Answers an even better place by editing questions, answers or comments. If needed, they can also remove content. Thanks to all of our Editors for all their hard work. You can read more about what they do in Guidelines for Editors on MATLAB Answers.

Image

Fall Contest Starts Wednesday

Image

It’s that time again! The Fall Contest begins at noontime Natick time/16:00 UTC, Wednesday November 2. Please join us for another fun season testing your MATLAB skills against other members of our community.

If you haven’t played before, read about past contest winners in our Hall of Fame, or watch Ned as he talks about how the contest team creates the game each season. We hope to see you online!

Happy Anniversary Ned!

If you’ve been part of the MATLAB Central community for a while, you’ve probably read blog or newsgroup posts, watched a video or downloaded File Exchange submissions from Ned Gulley, one of the founders of our community. Ned is celebrating his 20th anniversary at MathWorks.

Please join us in wishing him a very happy anniversary!

October 24th, 2011

Function Name Case Sensitivity in MATLAB R2011b

I can barely remember a MATLAB version that did not produce an inexact case match warning if you used the wrong capitalization of a function name. Now, the days of willy-nilly capitalization in MATLAB are over. Starting in R2011b, that long-time warning is now an error.

Here is the warning message in R2010a by calling “foo.m” with the command “Foo“:

Warning: Could not find an exact (case-sensitive) match for 'Foo'.
../foo.m is a case-insensitive match and will be used instead.
You can improve the performance of your code by using exact
name matches and we therefore recommend that you update your
usage accordingly. Alternatively, you can disable this warning using
warning('off','MATLAB:dispatcher:InexactCaseMatch').
This warning will become an error in future releases.

As promised, R2011b is the future release where this is now an error:

Cannot find an exact (case-sensitive) match for 'Foo'.
Do you want: foo
(in ../foo.m)?

This error identifier for this message is the same as the old warning: 'MATLAB:dispatcher:InexactCaseMatch'. If you still have any misspelled functions in your code, they should be spot by running the code and looking for these errors. Before launching your main script, run the command:

dbstop if error MATLAB:dispatcher:InexactCaseMatch

and your program will pause whenever this error occurs.

October 17th, 2011

R2011b Command Window Formatting Improvements

In this latest release we have a number of new formatting improvements in the MATLAB Command Window.
Easier to read errors
In old releases if there was an error when running a file, MATLAB would display an error like:

??? Error using ==> myfun2 at 1

As of R2011b, the formatting is different so it’s easier to read, and to navigate to the issue. In the same red text, it will now be formatted like:

New Error formatting

The function name will appear as a link that opens the doc page for that function, if available. The line number (if not a built-in a function) will be a link that opens that file in the Editor.

Orange Warnings
Warning text that appears in the command window will be colored orange to make them easier to spot. Like almost all our colors, this is configurable in the Preferences window if you have trouble seeing it: File -> Preferences -> Colors -> MATLAB Command Window colors.

Orange-colored Warnings in MATLAB R2011b

Formatted Help
Help displayed in the command window now bolds the function name as it appears in the help text.

Bold function names in help text

October 3rd, 2011

Comparison Tool Updates in R2011b

This week I’d like to welcome back guest poster, Malcolm Wood, to describe the enhancements to the File and Folder Comparison tool.

Over the last few releases we have made some major enhancements to the Comparison Tool in MATLAB, giving you more flexibility over what you can compare, more detail about the differences, and in some cases the ability to merge changes from one file to another.

In previous releases you could compare folders with other folders, ZIP-files with other ZIP-files, and Simulink manifest files with other Simulink manifest files. But since R2010b you can compare any of these with any other, treating each as a container for a list of files. So if you created a back-up of your work in a ZIP-file one day, you can use the Comparison Tool to examine the differences between the back-up and the folder containing your current work:

Comparison of backup folder

In R2011a we implemented some improvements to the MAT-file comparison report. It now shows the data types and sizes of your variables, and there’s the option to “merge” the differences between the files (1), i.e. to copy a variable from one file to the other. Be careful with this, because there’s no easily accessible “undo” feature for MAT-file merge. Instead, a back-up file is created to help you in case you make a mistake, and the report includes instructions on how to recover the previous values (2).

Comparison of backup MAT file

The other major new capability here is the option to compare the contents of the variables. Clicking the little magnifying glass icon (3) opens the “Variable Comparison” window. There are several different views, depending on the data type. Here is how it looks for a structure:

Comparison of variable contents

And by double clicking on a field in the structure you can compare the values inside. This is how it looks for the “hand2” field, which is a numeric array:

Comparison of a numeric array

We have also introduced some features to make it easier to concentrate on the important changes between text files. In R2010b we made it possible to ignore differences that involve only the number of “whitespace characters” in a line or between lines (4). So if all you did was change the indentation in your MATLAB code, these won’t show up as differences, leaving you to focus on changes which actually matter to your results. And in R2011a we made it possible to hide sections of the file which contain no changes (5), saving you a lot of scrolling if you are looking at only a few changes among thousands of lines of text.

Comparison of text files, hiding sections

Those of you who work on both Windows machines and Linux or Unix machines may be familiar with the problem of trying to compare files which use different types of end-of-line character. Some differencing tools will show every line as different, making it impossible to see where the actual text has changed. Others will ignore the end-of-line characters, perhaps leaving you scratching your head as to why two files of different sizes are reported as being identical by your differencing tool.

In R2011b we have two features to help you. Firstly, when comparing files as text and finding no differences to display, MATLAB will also check the sizes of the files and include the result in the report (6).

Comparison of text files, detailed report

Secondly, we enhanced the “Binary Comparison” report so that it can show the individual bytes that are different. By clicking the “New Comparison” button (7) and choosing “Binary Comparison” in the dialog you can generate a report like this one which enables you to see the additional carriage-return bytes (8):

Comparison of binary files

September 27th, 2011

MATLAB Tour 2011 Begins in Boston

MATLAB Tour 2011

The MATLAB Tour 2011 kicked off yesterday here in Boston! I had the privilege to attend this awesome one-day event. Here are my notes:

Keynote Presentation
Practicing data driven research is not easy. You have too much data to analyze or you don’t know how to validate your models with your data. The keynote demonstrated how you can use MATLAB and Simulink to tackle these common challenges. One demo used Parallel Computing Toolbox to speed up the analysis of large meteorological data sets and the other demo employed Model-Based Design to bring hybrid cars from conception to production. Don’t worry if you don’t know much about meteorology or hybrid car design, as the examples are used to illustrate how MathWorks tools can help you practice data driven research.

MATLAB and Simulink updates
Following the keynote, the MATLAB Today presentation covered many noteworthy MATLAB features introduced in recent years. I have listed my favorite ones here:

I know this blog is catered to MATLAB users, but some of the Simulink updates are also very intriguing.

Afternoon Sessions
The afternoon sessions focused on specific topics and workflows in MATLAB or Simulink. I attended two sessions.

Data-Fitting Techniques with MATLAB
If you are interested in questions like “Which mathematical model do I use?” or “Which parameters are most important in my model?” you will want to join the data fitting session and learn some MATLAB techniques and functions. You can get an abridged version of the material in this webinar.

Generate, Verify, and Integrate C Code from Your MATLAB Algorithms
If you are curious to see MATLAB Coder in action, this session provides a walkthrough of integrating your application into a C environment. There are some serious time savings using this workflow.

Final Thoughts
Aside from learning new features at this event and win some prizes, it is a great opportunity to network. I certainly enjoyed my conversations with the attendees. Take advantage of MATLAB Tour 2011 by attending at one of these locations!

September 19th, 2011

A Little Reminiscing on College

Chilly mornings and turning leaves reminded me of my college days at Cornell. A long fourteen years ago I was an engineering freshman, uncertain if I wanted to learn electrical engineering, computer science, or material science, or if I should forget the whole thing and go into theatre instead. Even now, I still haven’t made up mind: I’m a software developer despite having degrees in electrical engineering and neuroscience.

Unlike most of my peers, my first experience with MATLAB came in my first semester. I took a mid-level computational analysis class, foolishly ignoring its perquisites. I had to buy MATLAB 5.0 student version in the campus bookstore for $99. I’ve previously posted my answer to the first homework assignment. I aced that first problem set, but the class got exponentially harder as the semester wore on. I wish had tutorials like these when I was new user (http://www.mathworks.com/academia/student_center/tutorials/) .

Mac command window, r9

Two sophomore-year classes sealed me to electrical engineering and signal processing: Digital Electronics Lab, where we programmed logical circuits with NANDs and ORs, etc., and Signals and Systems, where I first learned about impulse responses and FFTs. Those are two of the few classes where I can still recall what I learned. In later signal processing classes I relied on MATLAB to find filter coefficients, determine stability and calculate and visualize (and hear) outputs of various filter algorithms. It’s too bad I didn’t have the Filter Design Toolbox then!

But it was the project courses in my junior and senior years that I found most impactful. Bruce Land’s embedded systems class in particular was my favorite. Thanks to the professor’s foresight my final project has been immortalized on the web. From this page you can see my early skills in web-design, Photoshop, and GUI building. In particular this project was an early stop on a continuing theme in my life: building systems with remote MATLAB processing. Warning: it may be a bit NSFW and does not reflect my current opinions.

The professor for that course also worked in the Neurobiology department. Between his influence and few other courses in computational psychology, bioengineering and a EE lab where we built EKG analyzers, I decided my next step was to go to grad school in Neuroscience. If you’re ever in Cornell’s engineering library, you can check out my thesis… it’s filled with MATLAB code modeling fish brains. It was this detour into biology that kindled my love of data analysis and visualization, which got me to come to MathWorks to help build a better MATLAB. Speaking of which, we’re still hiring: http://www.mathworks.com/company/jobs.

If you’re in college, or at least in heart, tell us about your MATLAB experiences below.



MathWorks
Mike works on the MATLAB Desktop team.

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