"Double for loop", question
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
a=[1 2];
b=[3 4];
n=length(a); % length(a)=length(b)=n
for i=1:n
for j=1:n
R(i)=a(j)*b(i);
end
end
% With the above R(i)=a(j)*b(i) i received 2 results in a form :
% [a(2)*b(1) , a(2)*b(2)] or [2*3 , 2*4] or [6,8].
% i can see that "b" varies following 1:n, but "a" is not
% varies and stay constand, as "n".
% Now, if i change R(i)=a(j)*b(i) to R(i)= R(i) + a(j)*b(i) :
>> R=zeros(2,1);
>> for i=1:n
for j=1:n
R(i)=R(i)+a(j)*b(i);
end
end
% i receive 2 results in a form :
% [a(1)*b(1) +a(2)*b(1) , a(1)*b(2) +a(2)*b(2)]
% or [1*3 + 2*3 , 1*4 + 2*4]
% or [3 + 6 , 4 + 8] or [9,12].
% I cannot understand, how adding R(i) in the right side of
% R(i)=a(j)*b(i), [in order to become R(i)=R(i)+a(j)*b(i)]
% make results from :
% a(2)*b(1) and a(2)*b(2)to :
% a(1)*b(1) +a(2)*b(1) and a(1)*b(2) +a (2)*b(2).
% It seems that adding R(i) in the right side, add a(1)*b(1) to the previous
% first result and a(1)*b(2) to the previous second result. "b" varies again
% following 1:n, and "a" stay constand but not as "n", like first, but as
% 1.
% Can somebody explain me, with example, how it works ?
0 Kommentare
Antworten (3)
Dyuman Joshi
am 15 Mai 2022
Bearbeitet: Dyuman Joshi
am 15 Mai 2022
Your data is being overwritten as the for loops runs.
For the 1st for loop
for i=1:n
for j=1:n
R(i)=a(j)*b(i);
end
end
As your j varies to 1 to n, the value of i is fixed. So the value of R(i) is overwritten as the for loop of j runs. It will store the last updated value corresponding to j i.e. n (a(n)*b(i))
That is what exactly you are obtaining - (%[a(2)*b(1) , a(2)*b(2)])
%Similarly for the 2nd for loop
R=zeros(2,1); %It should be (2,2) here
for i=1:n
for j=1:n
R(i)=R(i)+a(j)*b(i);
end
end
Here R(i) is initially 0. As the loop runs the value gets updated by the relation you have specified.
As the j for loop runs here's how your loop is modified
i=1
j=1;
R(1)=R(1)+a(1)*b(1) %which is 0 + a(1)*b(1) = a(1)*b(1)
j=2;
R(1)=R(1)+a(2)*b(1); %which is a(1)*b(1)+a(2)*b(1)
i=2
j=1;
R(2)=R(2)+a(1)*b(2) %which is 0 + a(1)*b(2) = a(1)*b(2)
j=2;
R(2)=R(2)+a(2)*b(2); %which is a(1)*b(2)+a(2)*b(2)
0 Kommentare
Kraka Doros
am 16 Mai 2022
1 Kommentar
Dyuman Joshi
am 17 Mai 2022
You need to understand how nested for loops work. There are many resources available on the internet which will help you understand. I suggest looking it up on YouTube, it will be explained with help of examples.
No one here will dedicate time to teach you. We can only help you solving a problem.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!