MATLAB: Does MATLAB not allow this assignment with the + operator

argumentsarraycomma-separated listerrorinputintuitiveMATLAB and Simulink Student Suiteoutputsize;sumunintuitive

Please see these results:
K>> [EndX,EndY,EndZ] = size(planneddose)
EndX =
135
EndY =
180
EndZ =
129
K>> size(planneddose)+[1 1 1]
ans =
136 181 130
K>> [EndX,EndY,EndZ] = size(planneddose)+[1 1 1]
Error using +
Too many output arguments.
I understand what is shown here is some functionality that calls multiple outputs for multiple inputs, whereas size(…)+[…] returns only a single array, but I think this use is intuitive and MATLAB should add it as a feature in the next release. (That is to say, I encounter this problem fairly often…) Is there a better way to accomplish this task, or must I add 1 to each using three additional commands?

Best Answer

Consider this:
planneddose = zeros(135, 130, 129, 2);
[EndX,EndY,EndZ] = size(planneddose) %works
EndX =
135
EndY =
130
EndZ =
258
>> size(planneddose)+[1 1 1]
Matrix dimensions must agree.
and consider
planneddose = zeros(135,130);
[EndX,EndY,EndZ] = size(planneddose)
EndX =
135
EndY =
130
EndZ =
1
>> size(planneddose)+[1 1 1]
Matrix dimensions must agree.
But in both cases assigning size(planneddose) to three variables was legal.
This is because size() looks at the number of output arguments to figure out the values it should output. In the case of three outputs, it outputs the first two dimensions into the first two variables and it outputs the product of all remaining dimensions in the third variable. This does not mean that the size "is" three dimensions: it is how size is defined. In the case of a single output, it outputs the individual dimensions as a vector, giving all of non-scalar leading dimensions explicitly, minimum two dimensions.
The case of size(planneddose)+[1 1 1] is the single output case, so it outputs a vector of values, of whatever length is appropriate. If you try to assign the resulting vector to three variables you have a problem because you do not have three sources.
There is no way in MATLAB to say that you want multiple outputs of a call or expression to be grouped together into individual elements of some data structure that you can then manipulate as if only a single variable had been returned. You cannot, for example, write
{size(planneddose)}
to get a cell array of the individual outputs from planneddose: this call will consider size() to have a single output so would create a cell array with a single element which is a vector of the dimensions. You cannot select a single output other than the first output either -- no way to do the equivalent of
function {local c; [~, c, ~] = size(planneddose); return c}
as an expression -- no way to write size(planneddose)#2 + 1 to get the second output and add 1 to it. You can have multiple assignments only in the case where the left hand side of an assignment has multiple outputs and the right hand size is a single call or single expansion.