Hi, I have a question. I wanna write code for matlab with this formula.
I confused in loop. My code:
A = [ 0.1 0.2 0.3 0.4
0.4 0.5 0.6 0.7
0.8 0.9 1.0 1.0
0.8 0.9 1.0 1.0];
[i,h]=size(A);
B = [ 0 1 0 1 0 1
1 0 0 1 0 0
0 0 1 1 0 0
1 0 0 0 0 1];
[h,j]=size(B);
mat=zeros(i,j);
temp=zeros(i,j);
for c=[1:j]
for r=[1:i]
temp(r,c)=A(r,r)*B(r,c);
mat=mat+temp;
end
end
I'm not sure of this code, is this right?

 채택된 답변

Stephen23
Stephen23 2018년 7월 25일
편집: Stephen23 2018년 7월 25일

0 개 추천

"is this right?"
No.
The formula is for basic matrix multiplication, so you can just use the inbuilt and very efficient mtimes:
A*B
If you really want waste time writing nested loops, then try this:
A = [ 0.1 0.2 0.3 0.4
0.4 0.5 0.6 0.7
0.8 0.9 1.0 1.0
0.8 0.9 1.0 1.0];
B = [ 0 1 0 1 0 1
1 0 0 1 0 0
0 0 1 1 0 0
1 0 0 0 0 1];
S = [size(A,1),size(B,2)];
D = nan(S);
for ii = 1:S(1)
for jj = 1:S(2)
tmp = 0;
for k = 1:size(A,2)
tmp = tmp+ A(ii,k)*B(k,jj);
end
D(ii,jj) = tmp;
end
end
disp(D) % nested loops
disp(A*B) % simpler and much more efficient

추가 답변 (0개)

카테고리

도움말 센터 및 File 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