"Double for loop", question
    8 views (last 30 days)
  
       Show older comments
    
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 Comments
Answers (3)
  Dyuman Joshi
      
      
 on 15 May 2022
        
      Edited: Dyuman Joshi
      
      
 on 15 May 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 Comments
  Kraka Doros
 on 16 May 2022
        1 Comment
  Dyuman Joshi
      
      
 on 17 May 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.
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!