19

Possible Duplicate:
How do I do multiple assignment in MATLAB?

So let's say I have a vector p = [1 2 3]. I want a command that looks like this:

[x y z] = p;

so that x = p(1), y = p(2), and z = p(3).

Is there an easy way to do this?

Community
  • 1
  • 1
rlbond
  • 65,341
  • 56
  • 178
  • 228
  • 3
    Duplicate: http://stackoverflow.com/questions/2740704/is-there-anything-like-deal-for-normal-matlab-arrays, which is itself a duplicate of http://stackoverflow.com/questions/2337126/multiple-assignment-in-matlab – mtrw May 23 '10 at 21:02

3 Answers3

29

Convert to cell array.

pCell = num2cell(p);
[x,y,z] = pCell{:};
Jonas
  • 74,690
  • 10
  • 137
  • 177
2

You can use deal:

[x y z] = deal( p(1), p(2), p(3) )

Nicholas Palko
  • 813
  • 3
  • 11
  • 21
1

Well, turns out there's no way to one-line this, so I wrote a function.

function varargout = deal_array(arr)
    s = numel(arr);
    n = nargout;

    if n > s
        error('Insufficient number of elements in array!');
    elseif n == 0
        return;
    end

    for i = 1:n
        varargout(i) = {arr(i)}; %#ok<AGROW>
    end
end
rlbond
  • 65,341
  • 56
  • 178
  • 228