# How do I create a matrix C that is comprised of values from matrices A and B, using a nested for loop?

8 views (last 30 days)
TFL on 19 May 2021
Answered: Kartikay Sapra on 19 May 2021
Hello, I have a question that says:
Where Cij is a 4x4 matrix and Cij= aij + bij for 1 =< i,j =< 2
aij - bij for 3 =< i,j =< 4
for all other values = 0
aij and bij are elements of the matrices A and B, use for loops.
Below i have given the matrices of A and B, I have also attempted this two ways, one includes a for loop but doesnt work. The other doesn't include a for loop but does work. Is there a way I can have it include a for loop and work haha, thanks for any help!
This way works, but no for loop:
code{A = [2 2 3 4; 1 0 1 1; 5 2 1 2; -1 2 -1 2];
B = [2 3 4 5; -1 0 2 2; 7 2 1 4; 2 0 1 2];
C = zeros(4);
a1 = A(1:2,1:2);
b1 = B(1:2,1:2);
a3 = A(3:4,3:4);
b3 = B(3:4,3:4);
sub = A(3:4,3:4)-B(3:4,3:4);
Z = zeros(2);
C = [add Z; Z sub]
% This way the code works but doesn't give the correct matrix for C, but i think something similar to this method is what the % quesiton is asking, includes for loop:
for A=1:2
for B=1:2
C(A,B)=A+B;
end
end
for A=3:4
for B=3:4
C(A,B)=A-B
end
end
% I'm sorry if it's an easy fix, any help is greatlu appreciated!

Girijashankar Sahoo on 19 May 2021
C=zeros(4)
A = [2 2 3 4; 1 0 1 1; 5 2 1 2; -1 2 -1 2];
B = [2 3 4 5; -1 0 2 2; 7 2 1 4; 2 0 1 2];
for i=1:4
j=1:2
C(i,j)=A(i,j)+B(i,j)
end
for i=1:4
j=3:4
C(i,j)=A(i,j)-B(i,j)
end

### More Answers (1)

Kartikay Sapra on 19 May 2021
C = zeros(4)
A = reshape(1:16, 4, 4)
B = reshape(17:32, 4, 4)
C(1:2, 1:2) = A(1:2,1:2) + B(1:2,1:2);
C(3:4, 3:4) = A(3:4,3:4) - B(3:4,3:4);
C
You were on the right path!
Remember that indices while iterating i and j would be same for all A, B and C. So we can use the MATLAB matrix slicing properties.