easy indexing lon-loop versus loop
Mostrar comentarios más antiguos
Hello, I have what I think is an easy indexing question, that has me scratching my head. I set up a simple moving average as such:
% the MA depth
Ml=16;
% the input data
x=[ zeros(1,Ml) 1:10 9:-1:7 8:10 9:-1:7 8:10 9:-1:7 8:10 9:-1:7]; % sequence to average out
% storage for output
y= zeros(1,length(x)+Ml);
%index
n= [Ml+1:length(x)];
%moving average
y(n)= y(n-1) + x(n)/Ml - x(n-Ml)/Ml;
which gives the wrong value for y(n). If I implement as a loop, it works fine.
% storage for output
yl= zeros(1,length(x)+Ml);
for n= Ml+1:length(x)
yl(n)= yl(n-1) + x(n)/Ml - x(n-Ml)/Ml
end
what is wrong with the non-loop version?
1 comentario
stephen williams
el 29 de Mzo. de 2021
Respuestas (1)
Bob Thompson
el 29 de Mzo. de 2021
I think the issue is with your loop definition. You define y1 to be length(x)+M1 long, but n is defined from M1+1 to length(x). I assume you were intending to do 1+M1 to length(x)+M1, but you will need to add the M1 to both sides of the colon.
% storage for output
yl= zeros(1,length(x)+Ml);
for n= Ml+1:length(x)
yl(n)= yl(n-1) + x(n)/Ml - x(n-Ml)/Ml
end
4 comentarios
stephen williams
el 29 de Mzo. de 2021
Bob Thompson
el 29 de Mzo. de 2021
Oh, the issue is because you're trying to do all the calculations at once, so as far as the outside the loop calculations are concerned, the y(n-1) = 0 no matter what you want y(n-1) to be. To write it out a bit more orderly:
1) Define initial values of everything, M1, x(an array of values), y(zeros), n(an array of values).
2) Calculate y using [M1, x(an array of values), y(zeros), n(an array of values)].
The loop wouldn't run into this issue, because you're sequentially calculating each of the values of y, so y(n-1) will have a chance to be defined before y(n) gets calculated.
stephen williams
el 1 de Abr. de 2021
stephen williams
el 1 de Abr. de 2021
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!