How do you loop across rows of an array without overwriting calculated values?

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

Please use the "{} Code" button to post code in a readable format. Thanks.
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.?
yes, the first option- calculating the average of rows 1-30, then 31-60, etc.

Sign in to comment.

 Accepted Answer

The loop version:
increment = 30;
numblocks = ceil(size(A, 1)/increment);
avg = zeros(numblocks, 1);
for idx = 1 : numblocks
M = A(idx*increment-increment+1 : min(size(A, 1), idx*increment), 2); %The min operation makes sure you don't select element past the end of the array for the last block which may have less than increment elements
avg(idx) = nanmean(M);
end
The better matlab non-loop version:
increment = 30;
avg = nanmean(reshape(A(1:end-mod(end, increment), 2), increment, [])).'; %deal with all blocks that are exactly the length of increment
avg = [avg; nanmean(A(end-mod(end, increment)+1:end, 2))]; %deal with last block that is too short
Note that since R2015a (I think) nanmean(x) can be replaced by mean(x, 'omitnan') which does not require any toolbox.

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

Tags

Asked:

on 2 Feb 2017

Edited:

on 2 Feb 2017

Community Treasure Hunt

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

Start Hunting!