How do you loop across rows of an array without overwriting calculated values?
Mostrar comentarios más antiguos
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 comentarios
Jan
el 2 de Feb. de 2017
Please use the "{} Code" button to post code in a readable format. Thanks.
Guillaume
el 2 de Feb. de 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
el 2 de Feb. de 2017
Respuesta aceptada
Más respuestas (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
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!