views:

82

answers:

2

When dealing with cell arrays, I can use the deal() function to assign cells to output variables, such as:

[a, b, c] = deal(myCell{:});

or just:

[a, b, c] = myCell{:};

I would like to do the same thing for a simple array, such as:

myArray = [1, 2, 3];
[a, b, c] = deal(myArray(:));

But this doesn't work. What's the alternative?

+3  A: 

One option is to convert your array to a cell array first using NUM2CELL:

myArray = [1, 2, 3];
cArray = num2cell(myArray);
[a, b, c] = cArray{:};

As you note, you don't even need to use DEAL to distribute the cell contents.

gnovice
Isn't this a one-liner? `[a,b,c] = num2cell(myArray){:}`
mtrw
@mtrw: Nope, that throws this error: `??? Error: ()-indexing must appear last in an index expression.`
gnovice
Oh interesting. It works in Octave. I guess the FOSS version can't afford to buy a temp variable.
mtrw
A: 

Not terribly pretty, but:

myArray = 1:3;
c = arrayfun(@(x) x, myArray , 'UniformOutput', false); 
c{:}
Richie Cotton
Actually, scratch that, the `arrayfun` call basically does the same thing as `num2cell`.
Richie Cotton
Here's a trick for shorter array/cell/Xfun calls: instead of 'UniformOutput',false, you can just have your anonymous function return a cell. c = arrayfun(@(x) {x}, myArray)
Andrew Janke