Process function at iterated linear indices

I'm trying to create a for loop that will calculate avg = mean(var(n:(n+500))) for all values of n. What I mean by that is that I want to average over the range from n to n+500 for each value of n, so if n has 500 values, I want to average over 500 different ranges. Mean is the function, var is a variable loaded to the workspace, and n is the linear index of values of the variable. I'm a pretty beginner-level matlab user and have almost no experience with looping, hence the difficulties.
Here's the code I have created, which yields only a single value for avg (the result for n=1):
load data.mat
[peaks, locs] = findpeaks(data1);
locs1 = locs-400;
locs2 = locs+400;
for locs = locs(1:end);
avg1 = mean(abs(data1(locs_minus:locs)));
avg2 = mean(abs(data1(locs:locs_plus)));
end
Any advice would be greatly appreciated. It seems like a very simple problem that I'm just too ignorant of matlab to figure out.

 채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 10월 4일

1 개 추천

avg1 and avg2 are over-written every time inside the loop.
outside of the for-loop, initialize avg1 and avg2 first:
avg1=zeros(size(locs));
avg2=zeros(size(locs));
Inside the for-loop, use
for k= 1:length(locs);
avg1(k) = mean(abs(data1(locs_minus:locs(k))));
avg2(k) = mean(abs(data1(locs(k):locs_plus)));
end

댓글 수: 1

Sarah
Sarah 2011년 10월 4일
Awesome! I tried something amazingly close to this, but the devil's really in the details. Thanks so much!

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

추가 답변 (0개)

카테고리

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

질문:

2011년 10월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by