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?
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:
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:I cannot comment other answers, so separate addition.
deal
can be used as a one-liner for non-scalars as well, of course if you already have them in separate variables, say:and now you deal them with one line:
However, if they are packed in one variable, you can only
deal
them if they are in a cell or structure array - withdeal(X{:})
for cell array anddeal(S.field)
for structure array. (In the latter case only one field is dealt, but from all structures in array.) With Matlab v.7+ you can useX{:}
andS.field
withoutdeal
, as noted in other answers.You might be looking for
resulting in
So you have a working one-liner.
To use the
num2cell
solution in one line, define a helper functionlist
:Note that
deal
accepts a "list" as argument, not a cell array. So the following works as expected:The syntax
c{:}
transforms a cell array in a list, and a list is a comma separated values, like in function arguments. Meaning that you can use thec{:}
syntax as argument to other functions thandeal
. To see that, try the following: