Merge multiple matrices with different columns into a single matrix

8 views (last 30 days)
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'.

Accepted Answer

Voss
Voss on 10 Nov 2023
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{:})
M = 6×5
173 326 327 0 0 3 1350 1351 0 0 175 332 333 334 335 9 1356 1357 1358 1359 176 335 336 337 0 11 1359 1360 1361 0
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);
173 326 327 0 0 3 1350 1351 0 0 175 332 333 334 335 9 1356 1357 1358 1359 176 335 336 337 0 11 1359 1360 1361 0

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!