# How to store values from nested for loop

75 views (last 30 days)
Berghan on 21 Sep 2021
Commented: Berghan on 28 Sep 2021
Im trying to make a nested loop but the value of A keeps adding up after each loop. I think i should store the value of A after each loop so it doesn't add up but im not sure how i do that.
clear all
N=10;
A=zeros(1,N);
for m = 1:N;
for n = 1:N
A(n,m) = A(n)+ sin(pi*(m+n)/(2*N))*sin((pi*m)/N);
end
end
A
Berghan on 28 Sep 2021
I asked a guy for help and he said that what i have done is almoste correct. For each iteration in the loop i get the value it had before + something, but then he says that it should be a number and not a vector. He says it's okay for it to be a vector aswell but then i have to sum it up afterwards.
here is a picture of the equation we are using. Im really trying to understand how I fix this code but I keep getting diffrent responds to whats wrong with the code. This is all new to me (both the double sum math and the coding) so it keeps getting messed up in my brain.
here is an uppdate on the code from the start of post if it helpt to clarify what I am trying to achieve.
Clear all
N = 10;
A = zeros(1,N);
for m = 1:N
for n = 1:N
A(n) = A(n) + sin(pi*(m+n)/(2*N))*sin((pi*m)/N);
end
B=A(n);
end
C=(B)/(N^2);
format long
display(C);

Rik on 28 Sep 2021
Edited: Rik on 28 Sep 2021
The first step to implement a summation in Matlab is very easy: just use a for loop. It is often possible to do this with a matrix operation, but let's first do the first step. %define constants here
N=10;
%Initialize the sum value to 0.
S=0;
%The sum-operator is very similar to a for statement:
%it defines a variable with a starting value and an end point.
for m=1:N
for n=1:N
%Now all variable are defined, you can simply write the inner part
%in Matlab syntax:
val=sin(pi*(m+n)/(2*N))*sin(pi*m/N);
S=S+val;
end
end
%Now do the product in front:
S=S*1/N^2;
format long,disp(S)
0.535931976159747
You can do this in one go, but you'll have to make sure the functions you're using inside the summation actually all support array inputs. Luckily for you, they do in this case (with minor modifications).
clearvars
N=10;
%define m and n as arrays:
[m,n]=ndgrid(1:N,1:N);
val=sin(pi*(m+n)/(2*N)).*sin(pi*m/N);
% ^
% This is the only place where two arrays interact.
% If in doubt, replace all / with ./ (same for * and ^)
% those will do the operation element by element, instead of a matrix
% multiplication.
S=(1/N^2)*sum(val,'all'); %or sum(val(:)) on old releases
disp(S)
0.535931976159747
Berghan on 28 Sep 2021
thank you!

R2021a

### Community Treasure Hunt

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

Start Hunting!