필터 지우기
필터 지우기

easy indexing lon-loop versus loop

조회 수: 1 (최근 30일)
stephen williams
stephen williams 2021년 3월 29일
댓글: stephen williams 2021년 4월 1일
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
stephen williams
stephen williams 2021년 3월 29일
This is a general indexing question. I thought if you preallocated the y(n) locations, I could calculate y(n) based on y(n-1) but that is not working right.
I could have made up some other difference equation.

댓글을 달려면 로그인하십시오.

답변 (1개)

Bob Thompson
Bob Thompson 2021년 3월 29일
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
stephen williams
stephen williams 2021년 4월 1일
thanks Bob.
Yes this issue is beucase I am trying to do the calculations all at once, and that is the question. I have aalternative ways to solve. I am trying to understand why this way does not work.
--Steve
stephen williams
stephen williams 2021년 4월 1일
thanks Bob.
Yes this issue is beucase I am trying to do the calculations all at once, and that is the question. I have alternative ways to solve. I am trying to understand why this way does not work.
--Steve

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by