2014-06-05 147 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