2

Possible Duplicate:
How do I do multiple assignment in MATLAB?

Say I have vector of values, v = 1:3,
and I want to assign the vector values to variables so a=1, b=2, c=3.
Trying to do so with [a, b, c] = deal(v) results with a=b=c=[1 2 3].

Does anyone know any one-liner for doing so, other than the obvious a=v(1), b=v(2), c=v(3)?

Community
  • 1
  • 1
shahar_m
  • 3,461
  • 5
  • 41
  • 61
  • 2
    See http://stackoverflow.com/questions/2740704/is-there-anything-like-deal-for-normal-matlab-arrays and http://stackoverflow.com/questions/2337126/how-do-i-do-multiple-assignment-in-matlab – Ramashalanka Apr 14 '11 at 10:01
  • 1
    I dare say this may be the most oft-duplicated MATLAB question on SO. Here are some more duplicates: [MATLAB Easiest way to assign elements of a vector to individual variables.](http://stackoverflow.com/questions/2893356/matlab-easiest-way-to-assign-elements-of-a-vector-to-individual-variables-close), [How do I extract matrix elements in matlab?](http://stackoverflow.com/questions/3743586/how-do-i-extract-matrix-elements-in-matlab-closed), [Pulling values out of a vector in MATLAB.](http://stackoverflow.com/questions/4672215/pulling-values-out-of-a-vector-in-matlab-closed) – gnovice Apr 14 '11 at 16:43

2 Answers2

1

Not a one-liner (I'm sure there is one out there!), but here's a function you could add to your MATLAB path that seems to do the right sort of thing:

function varargout  = deal2 ( inputVec ) 

for i = 1:nargout
    varargout{i} = inputVec(i);
end

end

Using this:

>> [a, b, c] = deal2([1 200 10])

a =

 1


b =

200


c =

10

This will work for any length input vector and number of outputs, provided the number of outputs is less than or equal to the length of the input vector.

Bill Cheatham
  • 11,396
  • 17
  • 69
  • 104
1

Not quite a one-liner, but close.

% Convert v to be a cell array, with each element in a different cell.
v = 1:3;
v2 = arrayfun(@(x) x, v, 'UniformOutput', false)

% Assign each cell to a different variable
[a, b, c] = v2{:}
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • 2
    You can just write `v2=num2cell(v)` for the same effect. See also the answers to the linked duplicate questions. – Jonas Apr 14 '11 at 14:07