tags:

views:

164

answers:

3

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?

+3  A: 

Convert to cell array.

pCell = num2cell(p);
[x,y,z] = pCell{:};
Jonas
Well, looks like this is the best I can do.
rlbond
A: 

You can use deal:

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

Nicholas Palko
Well, that's just as verbose as `x = p(1); y = p(2), z = p(3)`
rlbond
A: 

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

related questions