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.

Share:
49,484
user379362
Author by

user379362

Updated on November 29, 2020

Comments

  • user379362
    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
    Admin over 10 years
    Yes, they are supported. As you see, the comma syntax is the answer.
  • Admin
    Admin over 10 years
    OK. I just now removed the last line from your answer.
  • Admin
    Admin over 10 years
    I 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
    Bill over 3 years
    It 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 seems c must be pre-defined).
  • Andrew Janke
    Andrew Janke over 3 years
    Yep, 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.