20

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?

1

3 Answers 3

30

Convert to cell array.

pCell = num2cell(p); [x,y,z] = pCell{:}; 
Sign up to request clarification or add additional context in comments.

5 Comments

Well, looks like this is the best I can do.
Why defining pCell at all: [x,y,z] = num2cell(p){:};
@Philipp: In which version of Matlab can you do that? Octave has the feature, but Matlab doesn't have it (yet)
@Jonas You are so right. I am currently only using octave and I am not aware of the small differences.
@Philipp: No problem. Agreed that chain-indexing would really be nice.
2

You can use deal:

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

1 Comment

Well, that's just as verbose as x = p(1); y = p(2), z = p(3)
2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.