【问题标题】:Matlab array storing through loopMatlab数组通过循环存储
【发布时间】:2017-08-10 22:47:29
【问题描述】:
我有一个 for 循环,每个值 a{i} b{i} c{i} 每次都等于一个特定的数字。所以我想知道如何通过循环将所有这些值放入一个数组中。我使用的方式我的意思是这个[a{i};b{i};c{i}] 似乎它不起作用!如果我保留三个值中的 2 个有效,但我想要所有值中的数据 (a b c)
你可以看到下面的(伪)代码:
for i=1:number of cells
Cell{i}.Tri=[a{i};b{i};c{i}]
end
【问题讨论】:
标签:
arrays
matlab
loops
variable-assignment
cell-array
【解决方案1】:
这可以通过将 cellfun 与 cat 函数结合使用而无需 for 循环来完成。编辑:如 cmets 所述,cellfun 本身就是一个循环。
% Create all variables
a{1}=rand(10);
a=repmat(a,10,1);
b=a;
c=a;
% Add a cell array of equal size to a. The contents of each cell are the dimension along which to concatenate.
catarg=num2cell(ones(size(a)))
% Do the concatenation
d=cellfun(@cat,catarg,a,b,c,'UniformOutput',false);
【解决方案2】:
cell2mat 是你需要的:
a = num2cell(rand(1,10));
b = num2cell(rand(1,10));
c = num2cell(rand(1,10));
abc = cell2mat([a;b;c]);