开发者

MATLAB Easiest way to assign elements of a vector to individual variables [duplicate]

开发者 https://www.devze.com 2022-12-31 03:26 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How do I do multiple assignment in MATLAB?
This question already has answers here: Closed 11 years ago.

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?


Convert to cell array.

pCell = num2cell(p);
[x,y,z] = pCell{:};


You can use deal:

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号