How to store values from nested for loop
75 views (last 30 days)
Show older comments
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
Accepted Answer
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)
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)
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!