Loren on the Art of MATLAB

Turn ideas into MATLAB

dimsum in MATLAB 3

Posted by Loren Shure,

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!

Contents

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.


Get the MATLAB code

Published with MATLAB® R2019a

3 CommentsOldest to Newest

Roman Voronov replied on : 1 of 3
Yes, it is helpful. I think I asked for it via a feature request like 10 yrs ago. Lol
Andrew Stamps replied on : 2 of 3
Which, of course, now allows you to write:
y = all(A, 'all');
Only mildly confusing. ;-)
@Andrew - I had said this (but that's because you decided to create a variable named all. Not a great idea.) in sleep deprived state. Sorry! Yes, that code does look odd! @Roman - never say never :-) !

Add A Comment

Your email address will not be published. Required fields are marked *

Preview: hide