Take the 2-minute tour ×

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?

share|improve this question
Duplicate: stackoverflow.com/questions/2740704/…, which is itself a duplicate of stackoverflow.com/questions/2337126/… –  mtrw May 23 '10 at 21:02
add comment

marked as duplicate by Marc Gravell Feb 4 '11 at 9:05


3 Answers

up vote 8 down vote accepted

Convert to cell array.

pCell = num2cell(p);
[x,y,z] = pCell{:};
share|improve this answer
Well, looks like this is the best I can do. –  rlbond May 23 '10 at 21:19
add comment

You can use deal:

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

share|improve this answer
Well, that's just as verbose as x = p(1); y = p(2), z = p(3) –  rlbond May 23 '10 at 21:18
add comment

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

    for i = 1:n
        varargout(i) = {arr(i)}; %#ok<AGROW>
share|improve this answer
add comment
