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!
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.
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!).
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.
Is this new feature helpful to you? Let us know here.
Get the MATLAB code
Published with MATLAB® R2019a
10 CommentsOldest to Newest
y = all(A, 'all');Only mildly confusing. ;-)
S = sum(A) S = sum(A,'all') S = sum(A,dim) S = sum(A,vecdim) S = sum(___,outtype) S = sum(___,nanflag)
A = zeros(2,2,2); % consider two 3D matrices A(:,:,1) = [1:2;3:4]; A(:,:,2) = 2*[1:2;3:4]; B = zeros(2,2,2); B(:,:,1) = 2*[1:2;3:4]; B(:,:,2) = 3*[1:2;3:4]; Wanted = zeros(size(A)); % 3D matrix multiply for k = 1:size(A,3) Wanted(:,:,k) = A(:,:,k) * B(:,:,k); % performing matrix multiplication end % Which gives Wanted(:,:,1) = 14 20 30 44 Wanted(:,:,2) = 42 60 90 132 %So to perform the above operation let's consider the existing function mtimes() it would be a lot cooler just to simply use mtimes(A,B,3) % ^---- just denoting the third dimension I hope , I am clear now.