Clear Filters
Clear Filters

How to add matrix of different orders

3 views (last 30 days)
simone clochiatti
simone clochiatti on 24 Apr 2016
Answered: Peta on 24 Apr 2016
How can I add two matrix in which one is bigger than the other: A=[3 5 6 7;6 1 2 3] B=[2 4 5;5 7 8]
I want to make B the same order as A, adding zeros,in order to perform an addition between them, so B=[2 4 5 0;5 7 8 0] How do I perform this operation to B knowing the dimensions of A?

Answers (1)

Peta
Peta on 24 Apr 2016
If this dynamically changes over time I would calculate the difference in the width of the matrices like this first:
sizediff = size(A,2)-size(B,2);
And then use the horzcat command to pad the B variable, either by writing this:
B = horzcat(B,zeros(size(B,1),sizediff))
or this:
B = [B,zeros(size(B,1),sizediff)]
or potentially even this:
B = cat(2,B,zeros(size(B,1),sizediff))

Community Treasure Hunt

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

Start Hunting!