Define multiple variables at the same time in MATLAB?
49,484
Solution 1
Use comma-separated lists to get multiple variables in the left hand side of an expression.
You can use deal() to put multiple assignments one line.
[x,y] = deal(cell(4,8), cell(4,8));
Call it with a single input and all the outputs get the same value.
[x,y] = deal( cell(4,8) );
>> [a,b,c] = deal( 42 )
a =
42
b =
42
c =
42
Solution 2
It depends on the function that you use to generate the data. You can create your own function in MATLAB that has more than one output:
[a, b, c] = foo();
Many builtin function also have this option. But this must be supported directly by the returning function.
Author by
user379362
Updated on November 29, 2020Comments
-
user379362 over 3 years
I don't know if MATLAB can do this, and I want it purely for aesthetics in my code, but can MATLAB create two variables at the same time?
Example
x = cell(4,8); y = cell(4,8);
Is there a way to write the code something similar to:
x&y = cell(4,8);
-
Admin over 10 yearsYes, they are supported. As you see, the comma syntax is the answer.
-
Admin over 10 yearsOK. I just now removed the last line from your answer.
-
Admin over 10 yearsI even like your answer more. While not very verbose, the "How do I return these values in that format?" is not in the question.
-
Bill over 3 yearsIt says in the docs that "beginning with MATLAB Version 7.0 software, you can, in most cases, access the contents of cell arrays and structure fields without using the deal function." E.g.
[x,y] = c{:}
. (Doesn't really help in this case though since it seemsc
must be pre-defined). -
Andrew Janke over 3 yearsYep, that's only if you can do an expression which produces a "comma-separated list" of the values that you want, which pretty much requires indexing into a pre-existing variable. I'm not aware of any way to write literals or compose basic value-creation expressions like the author wants in a way that produces comma-separated lists, aside from just writing them out.