Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "unpack" a vector variable into several variables?

Tags:

matlab

In Python, a 3-tuple (for example) can be "unpacked" into three separate variables through assignment:

In [1]: triplet = (1, 'two', (True, True, True))

In [2]: first, second, third = triplet

In [3]: third
Out[3]: (True, True, True)

In [4]: second
Out[4]: 'two'

In [5]: first
Out[5]: 1

Is it possible to do something like this in MATLAB?

Everything I've tried fails. E.g.:

>> triplet = {1, 'two', [true, true, true]};
>> [first second third] = triplet
Too many output arguments.
like image 725
kjo Avatar asked Jul 04 '16 18:07

kjo


1 Answers

You can rely on cell expansion using {:} indexing which creates a comma-separated list which can be assigned to three output values.

[a, b, c] = triplet{:};

If triplet were a matrix instead, you could first convert it to a cell array using num2cell.

triplet = [1, 2, 3];
tripletcell = num2cell(triplet);

[a, b, c] = tripletcell{:};
like image 92
Suever Avatar answered Nov 05 '22 04:11

Suever