Merge multiple matrices with different columns into a single matrix
8 次查看(过去 30 天)
显示 更早的评论
I would like to combine several matrices with different columns (cell_test(:,1)) into one matrix by adding 0's (or rather []) in the missing values (see 'M' matrix).
cell_test = importdata("cell_test.mat"); %first column: matrices; second column: number of columns in the matrix
col = cell_test(1:3,2);
col = cell2mat(col);
col_max = max(col);
null_A = repmat(0,2,col_max-cell_test{1,2});
null_C = repmat(0,2,col_max-cell_test{3,2});
A_new = [cell_test{1,1} , null_A];
C_new = [cell_test{3,1} , null_C];
M = [A_new; cell_test{2,1}; C_new]; % result (where 0 become '[]' (possible?))
I would try to get the matrix 'M' as generically as possible, i.e. that I want to get that result even if I have multiple rows within 'cell_test'.
0 个评论
采纳的回答
Voss
2023-11-10
load cell_test
One way:
% get the size of each matrix in cell_test(:,1)
sz = cellfun(@size,cell_test(:,1),'UniformOutput',false);
sz = vertcat(sz{:});
% max number of columns:
col_max = max(sz(:,2));
% function that appends columns of zeros (to fill to col_max)
% to a matrix m of size s:
f = @(m,s)[m zeros(s(1),col_max-s(2))];
% apply that function to each matrix in cell_test(:,1)
% and store the results in cell array C:
C = cellfun(f,cell_test(:,1),num2cell(sz,2), ...
'UniformOutput',false);
% vertically concatenate all matrices in C together:
M = vertcat(C{:})
Another way:
% get the size of each matrix in cell_test(:,1)
sz = cellfun(@size,cell_test(:,1),'UniformOutput',false);
sz = vertcat(sz{:});
% keep track of row offsets, for where to assign each matrix into the
% result matrix:
rows = cumsum([1; sz(:,1)]);
% initialize result matrix:
M = zeros(rows(end)-1,col_max);
% loop over cell_test(:,1) and put each matrix in place in the result
% matrix:
for ii = 1:size(cell_test,1)
M(rows(ii):rows(ii+1)-1,1:sz(ii,2)) = cell_test{ii,1};
end
% show the result:
disp(M);
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!