is there any function for adding zero ? related toa other matrix

1 view (last 30 days)
Basically i want to compare 4 or 5 matrices but all of them are of diirérent sizes. But for the comparison they should of same size.
thats why i want to add zeros for the other positions .
A=[1 2 4 5; 2 6 3 5; 2 7 6 2]
B=[1 2 ; 3 2]
And the resultB
ResultB=[1 2 0 0;3 2 0 0;0 0 0 0]

Accepted Answer

Stephen23
Stephen23 on 20 Dec 2018
>> A = [1,2,4,5;2,6,3,5;2,7,6,2]
A =
1 2 4 5
2 6 3 5
2 7 6 2
>> B = [1,2;3,2]
B =
1 2
3 2
>> S = size(A);
>> R = B;
>> R(S(1),S(2)) = 0
R =
1 2 0 0
3 2 0 0
0 0 0 0

More Answers (1)

John D'Errico
John D'Errico on 20 Dec 2018
The problem is you need to decide how you want to pad the arrays.
For example, do you want to pad out by just extending each dimension with zeros? Or if B is too small by 2 in each dimension, then you might want to pad on the top AND bottom by 1 in each direction? Clearly the cases are differrent.
But the simple pad I mention in the first case is trivial.
Bpadd = B;
Bpadd(size(A,1),size(A,2)) = 0;
Bpadd
Bpadd =
1 2 0 0
3 2 0 0
0 0 0 0
The alternative pad is less trivial, but still easy enough. You would need to decide where to put the zeros first. So I might do this:
SA = size(A);
SB = size(B);
Bpadd = zeros(SA);
Bpadd(1:SB(1),2:SB(2)+1) = B;
Bpadd
Bpadd =
0 1 2 0
0 3 2 0
0 0 0 0

Community Treasure Hunt

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

Start Hunting!