17

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);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user379362
  • 341
  • 2
  • 5
  • 12
  • 1
    Seeking aesthetics in MATLAB code is always a battle uphill. But see my answer below. – Ole Thomsen Buus Mar 01 '11 at 17:37
  • 1
    If you want to initialize the variables with *different* values, then this is a duplicate of [How do I do multiple assignment in MATLAB?](http://stackoverflow.com/questions/2337126/how-do-i-do-multiple-assignment-in-matlab) If you want to initialize them with the *same* value, then [Andrew's suggestion](http://stackoverflow.com/questions/5158032/define-multiple-variables-at-the-same-time-in-matlab/5158206#5158206) to use [DEAL](http://www.mathworks.com/help/techdoc/ref/deal.html) is what you want. – gnovice Mar 01 '11 at 17:52

2 Answers2

34

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
Andrew Janke
  • 23,508
  • 5
  • 56
  • 85
  • It says [in the docs](https://www.mathworks.com/help/matlab/ref/deal.html) 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). – Bill Sep 02 '20 at 16:57
  • 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. – Andrew Janke Sep 03 '20 at 04:24
3

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.

Ole Thomsen Buus
  • 1,333
  • 1
  • 9
  • 24
  • Yes, they are supported. As you see, the comma syntax is the answer. –  Jan 08 '14 at 04:39
  • OK. I just now removed the last line from your answer. –  Jan 08 '14 at 04:40
  • 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. –  Jan 08 '14 at 04:43