2016-07-04 54 views
4

在Python中,3元組(例如)可以是「解包」分爲三個不同的變量賦值通過:如何「解開」一個矢量變量爲幾個變量?

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?

我試過的一切都失敗了。例如: -

>> triplet = {1, 'two', [true, true, true]}; 
>> [first second third] = triplet 
Too many output arguments. 

回答

5

你可以依靠使用{:}索引它會創建一個可以分配給三個輸出值comma-separated list細胞擴增。

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

如果triplet是一個矩陣,而不是,你可以先將其轉換爲使用num2cell單元陣列。

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

[a, b, c] = tripletcell{:}; 
+0

謝謝。我認爲「交易」是兩者中較爲一般的,因爲即使「三重」是「雙倍(1,3)」,它也會起作用。 – kjo

+0

@kjo不是,你必須提供每個輸出作爲輸入參數來處理。我更新了一個使用數字數組的示例。 – Suever