Matlab数组存储通过循环
Matlab array storing through loop
我有一个 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
cell2mat
是你需要的:
a = num2cell(rand(1,10));
b = num2cell(rand(1,10));
c = num2cell(rand(1,10));
abc = cell2mat([a;b;c]);
通过结合使用 cellfun 和 cat 函数,无需 for 循环即可完成此操作。编辑:如评论中所述,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);
我有一个 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
cell2mat
是你需要的:
a = num2cell(rand(1,10));
b = num2cell(rand(1,10));
c = num2cell(rand(1,10));
abc = cell2mat([a;b;c]);
通过结合使用 cellfun 和 cat 函数,无需 for 循环即可完成此操作。编辑:如评论中所述,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);