How do you loop across rows of an array without overwriting calculated values?
Show older comments
This is probably a very simple question/ quick fix, but I have an array I created in Matlab from an excel file. I am trying to calculate the average of the numbers in the second column every 30 rows, but can't seem to get this working- there should be 42 values (averages) as the output. What line(s) am I missing? Thanks in advance for the help (I am new to Matlab)!
count = 1
increment = 30
for i = count: increment;
M = A(1:increment,2); %A is the array(1266x2)
avg = nanmean(M);
count = count + 1;
end
3 Comments
Jan
on 2 Feb 2017
Please use the "{} Code" button to post code in a readable format. Thanks.
Guillaume
on 2 Feb 2017
Your loop does not make much sense. Nothing inside the loop depends on the loop counter i, so yo're just repeating the exact same operations 30 times.
Anyway, I'm unclear what "calculate the average of the numbers in the second column every 30 rows" mean. Is it calculating the average of rows 1-30 together, then 31-60 together, etc. or is it calculating the average of rows [1,31,61,91,...] together, then rows [2,32,62,92,...] together, etc.?
Anna K
on 2 Feb 2017
Accepted Answer
More Answers (1)
lenA = size(A, 1);
increment = 30;
lenOut = numel(count:30:lenA);
avg = zeros(1, lenOut); % Pre-allocate
iavg = 0;
for k = count:30:lenA
M = A(k:k+increment-1, 2); %A is the array(1266x2)
iavg = iavg + 1;
avg(iavg) = nanmean(M);
end
Or:
lenA = size(A, 1);
inc = 30;
step = count:30:lenA;
avg = zeros(1, numel(step)); % Pre-allocate
for k = 1:numel(step)
index = step(k);
avg(k) = nanmean(A(index:index+inc-1));
end
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!