Naming A Number of Variables in Matlab

27 Views Asked by At

If I need to get some variables values from a vector in Matlab, I could do, for instance,

x = A(1); y = A(2); z = A(3); 

or I think I remember I could do something like

[x, y, z] = A;

However Matlab is not recognizing this format. what was the correct syntax? Thanks!!

2

There are 2 best solutions below

1
On BEST ANSWER

@Thales is correct. If A happens to be a cell array rather than a matrix you could do something like this:

A = {1 2 3};
[x,y,z] = A{:}

But that is as close as it gets unless A is a function.

0
On

The right way to do it is:

x = A(1); y = A(2); z = A(3); 

This [x, y, z] = A makes no sense because A is not a function. You can use more variables in the left-hand side of an assignment as the outputs of a function. If A is a variable, then you just can't do it.

Edit: @horchler suggestion was to use a cell array to do it. Perhaps then you can write:

A = 1:3;
A = num2cell(A);
[x,y,z]=A{:}

And that will work. First you convert your array to a cell, then use the assignment to define the x, y and z variables. It is worth mentioning that this will do the trick for you, but that is not efficient. A cell array in MATLAB is much slower than an array itself and assign different elements of the array to different variables instead of using cell arrays will run faster though.