How do I do multiple assignment in MATLAB?

Benjamin Oakes picture Benjamin Oakes · Feb 25, 2010 · Viewed 43.6k times · Source

Here's an example of what I'm looking for:

>> foo = [88, 12];
>> [x, y] = foo;

I'd expect something like this afterwards:

>> x

x =

    88

>> y

y =

    12

But instead I get errors like:

??? Too many output arguments.

I thought deal() might do it, but it seems to only work on cells.

>> [x, y] = deal(foo{:});
??? Cell contents reference from a non-cell array object.

How do I solve my problem? Must I constantly index by 1 and 2 if I want to deal with them separately?

Answer

Ramashalanka picture Ramashalanka · Feb 25, 2010

You don't need deal at all (edit: for Matlab 7.0 or later) and, for your example, you don't need mat2cell; you can use num2cell with no other arguments::

foo = [88, 12];
fooCell = num2cell(foo);
[x y]=fooCell{:}

x =

    88


y =

    12

If you want to use deal for some other reason, you can:

foo = [88, 12];
fooCell = num2cell(foo);
[x y]=deal(fooCell{:})

x =

    88


y =

    12