Loren on the Art of MATLAB

Turn ideas into MATLAB


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

dimsum in MATLAB

As Steve noted in a recent post, several of the functions that operate along specific dimensions have been updated to add some new functionality, for example the function sum. (I also think he missed a great opportunity for a cool blog post title, which is only partly why I am writing about it now :^) ). Please read his post!


Summing Elements of an Array

As you likely know, MATLAB has a collection of functions that operate on inputs, treating the effective column vectors as individual units. There functions include sum, prod, cumsum, mean, to name a few.

Originally, you could only use these functions with a single input. And the operation (+, *, etc.) would occur along the first non-singleton dimension. This tripped people up enough and was inconvenient enough that we eventually added an optional dimension argument. And, if you wanted to apply the operation to the entire array, we taught you to string the input into a long column vector (A(:)) and apply the necessary function to this transformed array.

An Aside - the Engineering Rule of Thumb

We had a wonderful engineer here many years ago that taught me the "engineering rule of thumb". Either you disallow something always, you allow it once, or you always allow it. This got shortened to the "0, 1, or infinity rule". Look at the case of sum as a representative function. If you simply require the default behavior, you need not supply any additional arguments beyond the array itself (0), you can use an optional scalar argument (1) to specify the dimension to work on, and now you can have that optional argument be a vector of dimensions (infinity, theoretically - but you'll never fit that into MATLAB!).

Back to Dimensions

In R2018b we added a perhaps friendlier syntax for the func(A(:)) syntax, now func(A,'all'). This is in addition to allowing no dimension input, a scalar dimension input, or a vector of dimensions - 0, 1, infinity.

Here's the current list of functions to which these new input patterns apply.

Your Feedback

Is this new feature helpful to you? Let us know here.

Published with MATLAB® R2019a

  • print


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