How to store values from nested for loop
Afficher commentaires plus anciens
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
4 commentaires
Jan
le 21 Sep 2021
It is not clear what you want to achieve. Does "A(n)" means "A(n,1)" implicitly?
Berghan
le 22 Sep 2021
DGM
le 22 Sep 2021
This suggests that A is a 1xN vector:
A = zeros(1,N);
This says that A is a NxN matrix instead:
for m = 1:N;
for n = 1:N
A(n,m) = % ...
end
end
... but this
A(n)+ sin(pi*(m+n)/(2*N))*sin((pi*m)/N);
and your comment suggest that A is either a vector or is being addressed with linear indexing -- but if you're using linear indexing to address the matrix, why wouldn't it keep adding up?
I doubt you intend to use linear indexing, and I'm not sure if you're intending for the output to be a matrix either. The example you give is a simple 1-D scenario where the output of a particular iteration is a function of the prior result. The code above doesn't do that. It uses A(n,1) implicitly as Jan pointed out, because n in A(n) is treated as a linear index.
There are two points of uncertainty that I see:
- Is A supposed to be 1D or 2D?
- If 2D, to which element of A is "A(n)" intended to refer?
It's hard to guess what's intended. If the result isn't supposed to keep recycling values after each inner loop, then the behavior is probably supposed to only be working along one axis. For example, let's say you intend for a 2D output, where each element is a function of the element one row above. In other words, "A(n)" in the above expression for A(n,m) actually refers to A(n-1,m). Working on those assumptions:
N = 10;
A = zeros(N,N);
A(1,:) = sin(pi*(2:N+1)/(2*N)).*sin((pi*(1:N))/N);
for m = 1:N
for n = 2:N
A(n,m) = A(n-1,m) + sin(pi*(m+n)/(2*N))*sin((pi*m)/N);
end
end
A
% that whole thing simplifies to this
m = 1:N;
A2 = zeros(N,N);
A2(1,:) = sin(pi*(m+1)/(2*N)).*sin((pi*m)/N);
for n = 2:N
A2(n,:) = A2(n-1,:) + sin(pi*(m+n)/(2*N)).*sin((pi*m)/N);
end
immse(A-A2) % outputs are identical
Or maybe it's supposed to do something else. If the above assumption isn't close, we have to fall back to answering those two bulleted questions.
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

