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!