2014-06-05 146 views
0

有沒有一種方法可以編寫for循環,它會將給定數量的矩陣添加到單元陣列中。迭代矩陣到單元陣列中

`C1 = [];` 

的所以不必編寫大家出像:

`cell = {} 
cell = [cell C1]; 
cell = [cell C2]; 
cell = [cell C3]; 
cell = [cell C4];` 

其中C的數量是已知的。

回答

2

如果C矩陣的數量是已知的,那麼是的,你可以寫一個for循環來做到這一點。在循環的每次迭代中,命令字符串可建,然後評價:

N = 4; 
cellArray = cell(N,1); % pre-allocate memory for the array 
for i=1:N 

    % build the command string 
    cmd = ['cellArray{i} = C' num2str(i) ';']; 

    % evaluate the string 
    eval(cmd); 

end 

你可以單步執行代碼,看看cmd看起來像在每次迭代。請注意,有些開發人員對使用eval命令有一些擔憂。由於您正在構建要在每次迭代中運行的命令,因此它可以使調試(如果出現錯誤)更難一些。

+0

謝謝,這似乎是做我想做的。 – user3575908