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);
2
  • 1
    Seeking aesthetics in MATLAB code is always a battle uphill. But see my answer below. Commented Mar 1, 2011 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? If you want to initialize them with the same value, then Andrew's suggestion to use DEAL is what you want. Commented Mar 1, 2011 at 17:52

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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).
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.
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.

3 Comments

Yes, they are supported. As you see, the comma syntax is the answer.
OK. I just now removed the last line from your answer.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.