Write a program so that with help of 3 for-end loops we form a matrix C that will be equivalent to C= A*B - B*A

1 回表示 (過去 30 日間)
Let 2 matrices (A and B) be given in MatLab.Write a program so that with help of 3 for-end loops we form a matrix C that will be equivalent to C= A*B - B*A
  3 件のコメント
Bruno Luong
Bruno Luong 2022 年 4 月 29 日
@Jakub Devera matrix is 2D, and naive multipling two matrices requires 3 nested loops.
Jan
Jan 2022 年 4 月 29 日
編集済み: Jan 2022 年 4 月 29 日
This is a homework question. As usual, post, what you have tried so far and ask a specific question concern the remaining Matlab problem.
The actual problem is interesting. You can avoid to calculate A*B and B*A explicitly.
@Jakub Devera: If A*B and B*A is mathematically defined, A and B must be square matrices.

サインインしてコメントする。

回答 (2 件)

Srija Kethiri
Srija Kethiri 2022 年 5 月 2 日
Hi Iva,
From my understanding you want to to get a matrix C, where C = A*B - B*A. To get the matrix C it is possible only if A and B both are square matrices with same dimension.
The code for finding C is:
[c,d] = size(A);
[e,f] = size(B);
C = zeros(c,c);
if(c==d && e==f && c==e)
for i=1:c
for j=1:c
sum1 =0;
sum2 =0;
for p = 1:c
sum1 = sum1 + A(i,p)*B(p,j);
sum2 = sum2 +B(i,p)*A(p,j);
C(i,j) = sum1-sum2;
end
end
end
end
  2 件のコメント
John D'Errico
John D'Errico 2022 年 5 月 2 日
Please don't answer obvious homework assignment questions, when no effort was made or shown. This does not help the student. It only teaches them to post the rest of their homework on Answers, and that hurts the site.
Jan
Jan 2022 年 5 月 2 日
I agree with John.
Your code overwrites C(i,j) in each iteration of the inner loop. One variable would be enough for the accumulation.

サインインしてコメントする。


Matt J
Matt J 2022 年 5 月 2 日
編集済み: Matt J 2022 年 5 月 2 日
A=rand(4); B=rand(4); %synthetic input data
M={A,B;B,A};
mask=[1 1;1,-1];
for i=1:4
M{i}=mask(i)*M{i};
end
for i=1:2
M{i,1}=M{i,1}*M{i,2};
end
C=0;
for i=1:2
C=C+M{i};
end
C-(A*B-B*A)%Check the result
ans = 4×4
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by