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
Jan
2017년 2월 2일
Please use the "{} Code" button to post code in a readable format. Thanks.
Guillaume
2017년 2월 2일
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
2017년 2월 2일
채택된 답변
추가 답변 (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
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!