views:

313

answers:

3

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?

+1  A: 

DEAL is really useful, and really confusing. foo needs to be a cell array itself, I believe. The following seems to work in Octave, if I remember correctly it will work in MATLAB as well:

> foo = {88, 12}
foo =

{
  [1,1] =  88
  [1,2] =  12
}

> [x,y] = deal(foo{:})
x =  88
y =  12
mtrw
+2  A: 

What mtrw said. Basically, you want to use deal with a cell array (though deal(88,12) works as well).

Assuming you start with an array foo that is n-by-2, and you want to assign the first column to x and the second to y, you do the following:

foo = [88,12;89,13;90,14];
%# divide the columns of foo into separate cells, i.e. do mat2cell(foo,3,[1,1])
fooCell = mat2cell(foo,size(foo,1),ones(size(foo,2),1));
[x,y] = deal(fooCell{:});
Jonas
+4  A: 

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
Ramashalanka
Just a side note, I think you can only get away with not using deal( as in the first example) in Matlab 7+.
Justin Peel
Interesting. I didn't know that deal is unnecessary nowadays. However, I used mat2cell on purpose, since I assume that the OP might want to separate columns from each other.
Jonas
This is really good. But is there any way to have it all on one line? Maybe something like: `[x y] = num2cell(foo){:}` (Sorry, still confused by Matlab quite often.)
Benjamin Oakes
@Justin: good point, you need version 7.0 (2004) or later. @Jonas: true, `mat2cell` is good if you want to split up in different ways. @Benjamin: I'm not aware of a one line method, unless you use a cell to begin with; you can use `deal(88,12)` if you are starting from scalars. It'd be good if we stuff like `num2cell(foo){:}` for many Matlab commands.
Ramashalanka