Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab multiple variable assignments

Tags:

matlab

I would like to assign the values in a vector of length 2 to multiple variables. The output of size() is able to do this:

% works
[m,n] = size([0 0]);

However splitting this into two lines doesn't work:

sz = size([0 0]);
[m,n] = sz;
% returns:
%   ??? Too many output arguments.

What is special about the return value of size that is lost when it is assigned to a variable?

like image 864
benathon Avatar asked Dec 15 '22 19:12

benathon


2 Answers

Matlab's output arguments are interesting this way. A function can have a variable number of outputs depending on how many the ‘user’ asked for.

When you write

[m,n] = size([0 0]);

you are requesting two output arguments. Inside the function itself this would correspond to the variable nargout equal to 2.

But when you write

sz = size([0 0]);

the size function recognises that it's a single output argument, and gives you both m and n as a vector instead of two singleton outputs. This style of behaviour is (I think) generally uncommon in Matlab.

Also note that Matlab doesn't allow multiple arguments to break up vectors:

x = [1 1]
[y,z] = x

returns Too many output arguments.

like image 122
Will Robertson Avatar answered Dec 27 '22 00:12

Will Robertson


The custom function you introduced is quite an overkill and uses functions like eval which are considered bad practice. It can be done much shorter. That's all you need:

function [ varargout ] = split( Vector )

varargout = num2cell( Vector );

end

And because of varargout you have a variable-length output argument list and you don't need to edit your function for more argements.

It works for vectors as well as for matrices:

[a,b,c,d] = split( [1,2;3,4] )

a =  1

b =  3

c =  2

d =  4

If you don't like the matrix compatibility, include a condition and check the dimensions of the input vector.

like image 22
Robert Seifert Avatar answered Dec 27 '22 01:12

Robert Seifert