Loren on the Art of MATLAB

Turn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

What’s the Big deal?

So, what is the big deal? To start with, this week marks my 19th anniversary at MathWorks. Never would I have guessed back then what I am up to now, including talking about MATLAB with so many customers. I look forward to many more years working with MATLAB at MathWorks and meeting and working with so many wonderful customers.

In a recent post on the MATLAB newsgroup, Duane Hanselman mentioned that he found something interesting in the help for deal, namely the note:

In many instances, you can access the data in cell arrays and structure fields without using the deal function.
and he went on to ask when this was introduced. To find the answer, I did some archaeology in the MATLAB Release Notes and found some information in the notes for Release 14, MATLAB 7.

Why did we introduce this? Here are some of our thoughts from our design discussions:

  • Users either have to use deal or a loop to extract information from a cell array or a field of a struct array.
  • c{:} and a(:).fn both produce comma-separated lists in MATLAB. Before this change, you could enclose these expressions in square brackets ([ ]), curly braces ({ }), or parentheses for a function call (foo( )). Otherwise, they produced as many outputs as the length of the array input, each successively assigned to ans.
  • Because we were now allowing assignment with a comma separated list on the right hand side where it was not possible before, we were not going to break working code.
  • The idea seemed both natural and welcome when we spoke to some M programmers at MathWorks.

The biggest problem I see with this new construct is that it seems to have taken a while to get the exposure it deserves. While there is still clearly a role for deal, it's required less often than before MATLAB 7.

One code pattern I have seen deal used for is renaming variables. For example, you can swap the values of A and B with this:

    [B,A] = deal(A,B);

With the use of anonymous functions you can also accomplish the same outcome:

   swap=@(varargin)varargin{nargin:-1:1};

Now let's see what that does:

   a = 1;
   b = 2;
   c = 17;
   [a,b,c] = swap(a,b,c)

and the output looks like this:


a =

    17


b =

     2


c =

     1

There will be more in future articles on function handles, anonymous functions and nested functions. I have received suggestions for article topics from several of you and would love to gather even more input. Please keep the feedback coming!


  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.