nested for loop for moving average filter

Hello Everyone,
I want to implement nested for loop in MATLAB the first loop should run from 3 to n and inside this loop the second for loop should run for 1:5. My problem is I want to take averages of 5 numbers but a moving average. So i should start with average from elements 1 to 5 for first row, elements 2 to 6 for second row , elemets 3 to 7 for third row.
Please help me with this problem.
Thanks in Advance

댓글 수: 3

Jan
Jan 2012년 11월 29일
What have you tried so far? The text description seems to be clear enough to convert this directly to Matlab.
Jatin Arora
Jatin Arora 2012년 11월 29일
편집: Jatin Arora 2012년 11월 29일
The problem was the length of initial array is not fixed and also the length of number of neighbouring points is not fixed. So I was not able to put a constant value. I was able to solve the problem
for i = 3:end
j1=i-No;
j2=i+No;
for j = j1:j2
PtsSum(i,:)=PtsSum(i,:)+PathPntIn(j,:);
end
end
Now I am stuck at a different thing. So will put a new question.
You always have to decide what to do at the end when the window falls outside the signal. Looks like you want to just limit the window so that it never goes outside your signal. I think you need to do
for i = 2 : end-2 % not 3:end
where No is 2, which is the half width of a 5 element wide window.

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

답변 (2개)

Jan
Jan 2012년 11월 29일

2 개 추천

No loops required in Matlab:
n = length(x);
mx = (x(1:n-4) + x(2:n-3) + x(3:n-2) + x(4:n-1) + x(5:n)) / 5;

댓글 수: 1

Daniel Shub
Daniel Shub 2012년 11월 29일
I thought this would be faster than conv, but I was wrong. I wonder what the fastest method is for a moving average filter.

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

Daniel Shub
Daniel Shub 2012년 11월 29일

2 개 추천

While you can do this with a loop, MATLAB has some highly optimized commands for filtering. The simpliest is probably conv.
First create some dummy date
N = 20;
x = randi(10, N, 1);
The M point moving average filter is
M = 5;
y = conv(x, ones(M, 1));

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2012년 11월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by