如何有效地将不同大小的array
v row
和Column
单元格合并到matrix
中,用0填充向量?
例如,如果我有
A= {[1;2;3] [1 2 ; 1 3; 2 3] [1 2 3]};
我想要得到:
A=[1 0 0
2 0 0
3 0 0
1 2 0
1 3 0
2 3 0
1 2 3]
答案 0 :(得分:3)
您可以使用padarray
在vertcat
之前用零填充数组:
B = padarray(A{1},[0 3-size(A{1},2)],'post')
C = padarray(A{2},[0 3-size(A{2},2)],'post')
D = padarray(A{3},[0 3-size(A{3},2)],'post')
%//Note the 3-size(A{1},2)... The 3 comes from the number of columns you want your final matrix to be, and it cannot be smaller than the maximum value of size(A{N},2) in your case it is 3, since A{3} is 3 columns wide.
result = vertcat (B,C,D)
result =
1 0 0
2 0 0
3 0 0
1 2 0
1 3 0
2 3 0
1 2 3
你可以写一个循环遍历你的单元格或使用cellfun进行并行化。
在一个简单的循环中,它看起来像:
result = [];
for t = 1:size(A,2)
B = padarray(A{t},[0 3-size(A{t},2)],'post');
result = vertcat(result,B);
end