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.

 Risposta accettata

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 Commento

Awesome! I tried something amazingly close to this, but the devil's really in the details. Thanks so much!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by