如何“解包"一个向量变量变成几个变量? [英] How to "unpack" a vector variable into several variables?
本文介绍了如何“解包"一个向量变量变成几个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,可以通过赋值将3元组(例如)解包"为三个单独的变量:
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
是否可以在MATLAB中执行类似的操作?
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.
推荐答案
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{:};
如果triplet
是矩阵,则可以先使用num2cell
将其转换为单元格数组.
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{:};
这篇关于如何“解包"一个向量变量变成几个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文