MATLAB Easiest way to assign elements of a vector to individual variables [duplicate]
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
精彩评论