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

1 次查看(过去 30 天)
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]

采纳的回答

Stephen23
Stephen23 2018-12-20
>> 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

更多回答(1 个)

John D'Errico
John D'Errico 2018-12-20
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by