如何在 MATLAB 中将元胞数组中不同大小的行和列组合成矩阵
How to combine row and Column with different size in a cell array into matrix in MATLAB
如何高效地将不同大小的单元格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]
您可以简单地使用 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
如何高效地将不同大小的单元格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]
您可以简单地使用 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