I want to do multivariable assignment. I can do [a,b] = min([1 2 3])
but I can't do [a,b] = [1,2]
. Why? Is there any workaround?
Asked
Active
Viewed 126 times
1

piotrek
- 13,982
- 13
- 79
- 165
-
Examples in this PAQ http://stackoverflow.com/questions/9908398/octave-basics-how-to-assign-variables-from-a-vector – Cobusve Aug 08 '15 at 14:22
-
Please consider removing the Matlab tag since the accepted answer won't work there. My answer using `deal` would do the job in Octave and Matlab. – Matt Aug 08 '15 at 14:30
3 Answers
2
The [1,2]
on the right hand side of the assignment is interpreted as array with the two elements 1
and 2
.
If you want to do the multi-variable-assignment in one line, you can use deal
in Matlab. This should work in Octave as well according to the documentation here.
>> [a,b] = deal(1,2)
a =
1
b =
2
The advantage of using deal
is that it works in Matlab as well, where the solution with [a b] = {1 2}{:}
won't.

Matt
- 12,848
- 2
- 31
- 53
0
To adapt Cobusve's answer to Matlab, two lines are required:
>> h={5 6 7}
h =
[5] [6] [7]
>> [a b c]=h{:}
a =
5
b =
6
c =
7

Daniel
- 36,610
- 3
- 36
- 69