Concatenate matrices not the same size - without NaN

4 views (last 30 days)
Hello,
I am trying to concatenate several matrixes having different sizes (rows and columns).
In order to have the same number of rows and columns so they can be concatenated, I want all the non-existant values of the smaller matrices to fill up with a constant value, so that in the end, all matrices have the same dimensions, which are the greatest number of lines among all matrices by the greatest number of columns among the matrices.
So, to sum up: I have, for example, two matrices A = [1 2 3; 4 5 6; 7 8 9] and B = [1 2; 3 4], and I want a 3D-matrix C = [1 2 3; 4 5 6; 7 8 9] and [1 2 a; 3 4 a; a a a] (with 'a' a given constant).
I tried to do this with the fillmissing function, but it seems it only works when there are NaN in the matrices? Here my matrices are images so the pixels I want to add don't exist at all.
Is there an existing function for this, or do I have to do it "manually"?
Thank you!
Nicolas

Accepted Answer

Matt J
Matt J on 6 Mar 2021
Edited: Matt J on 6 Mar 2021
Is there an existing function for this
There is now:
a=NaN;
C = padcat(a, [1 2 3; 4 5 6; 7 8 9] , [1 2; 3 4] )
C =
C(:,:,1) = 1 2 3 4 5 6 7 8 9 C(:,:,2) = 1 2 NaN 3 4 NaN NaN NaN NaN
function C= padcat(padVal,varargin)
%Pad a list of matrices with padVal and concatenate
%
% C=padcat(padVal, Matrix1, Matrix2,...)
n=numel(varargin);
s=cellfun(@size,varargin,'uni',0);
smax=max(vertcat(s{:}));
C=repelem(padVal,smax(1),smax(2),n);
for i=1:n
C( 1:s{i}(1), 1:s{i}(2),i)=varargin{i};
end
end

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!