Trick to enlarge a matrix by padding it with zeros.
Image Analyst
on 10 Feb 2024
To enlarge an array with more rows and/or columns, you can set the lower right index to zero. This will pad the matrix with zeros.
m = rand(2, 3) % Initial matrix is 2 rows by 3 columns
mCopy = m;
% Now make it 2 rows by 5 columns
m(2, 5) = 0
m = mCopy; % Go back to original matrix.
% Now make it 3 rows by 3 columns
m(3, 3) = 0
m = mCopy; % Go back to original matrix.
% Now make it 3 rows by 7 columns
m(3, 7) = 0
1 Comment
Except that you have to first check and make sure that m is not already 2x5 or 3x7. Otherwise, you will accidentally overwrite the original data.
A more hazard-proof way of doing this is,
>> m = rand(2, 3) %initial matrix, m
m =
0.1004 0.5660 0.6003
0.4656 0.9291 0.3259
>> r=2; c=3; m(end+1:r,end+1:c)=0 %original matrix preserved
m =
0.1004 0.5660 0.6003
0.4656 0.9291 0.3259
>> r=3; c=7; m(end+1:r,end+1:c)=0 %original matrix padded
m =
0.1004 0.5660 0.6003 0 0 0 0
0.4656 0.9291 0.3259 0 0 0 0
0 0 0 0 0 0 0