How to make two different size matrix of same size

185 views (last 30 days)
I have two matrix of size:
A = (123 x 321 double)
A1= (123 x 320 double)
how can I make A1 matrix dimension same as of A dimension
  3 Comments
NotA_Programmer
NotA_Programmer on 2 May 2022
Any suggestions about using length function
A1(length(A)) = 0;
dpb
dpb on 2 May 2022
It's not a robust solution as noted in other Answer given the definiton of length() as max(size()) but in this case since both are longer in second dimension will work as desired by initial Q?
Would have to see actual code to see where went wrong to get the result you posit here.
Illustration of problem/issue -- small arrays to be able to visualize --
>> A=randi(10,3,4);
>> A1=randi(10,3);
>> whos A*
Name Size Bytes Class Attributes
A 3x4 96 double
A1 3x3 72 double
>> A1(:,length(A))=0;
>> whos A*
Name Size Bytes Class Attributes
A 3x4 96 double
A1 3x4 96 double
>>
size(A,2) > size(A,1) so the above produces desired result. This is case of original Q? so "works as intended".
Now try "t'other way 'round" --
>> A=randi(10,4,3);
>> A1=randi(10,4,2);
>> whos A*
Name Size Bytes Class Attributes
A 4x3 96 double
A1 4x2 64 double
>> A1(:,length(A))=0;
>> whos A*
Name Size Bytes Class Attributes
A 4x3 96 double
A1 4x4 128 double
>> A1
A1 =
8 7 0 0
7 10 0 0
10 1 0 0
8 3 0 0
>>
Ended up with unexpected result -- the augmented array actually is now larger in the second dimension that the first, not the same.
The most robust solution is that posted elsewhere -- test and use conditional branching depending upon what sizes actually are and which way trying to catenate.

Sign in to comment.

Accepted Answer

Voss
Voss on 2 May 2022
Don't use length to do that. length is the size of the longest dimension, so without knowing whether that's dimension 1 (number of rows) or dimension 2 (number of columns) of a matrix, you can't reliably use length to augment the matrix with zeros. Instead, use size, which tells you the size in all dimensions.
Here's one way (of many) to do it:
[m,n] = size(A);
[m1,n1] = size(A1);
if m < m1
A(m1,:) = 0; % extend A with rows of zeros, up to the number of rows of A1
elseif m > m1
A1(m,:) = 0; % extend A1 with rows of zeros, up to the number of rows of A
end
if n < n1
A(:,n1) = 0; % extend A with columns of zeros, up to the number of columns of A1
elseif n > n1
A1(:,n) = 0; % extend A1 with columns of zeros, up to the number of columns of A
end

More Answers (1)

dpb
dpb on 2 May 2022
A1=[A1 A(:,end)];
could be one alternate solution...there is no unique answer without additional conditions placed on expected output.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!