How can I use a for loop to index a vector, average the indexed values, and store the averages in another vector when the subsets are of different lengths?
2 次查看(过去 30 天)
显示 更早的评论
I have column vectors of CO2 flux values that were measured at a 5 minute frequency and correspdoning date/time vectors (Year, Month, Day, Hour, etc).
I am trying to create a for loop to subset each flux value by its corresponding hour, average the flux values for each subsetted hour (the lengths are not the same), and store the averaged values in a vector to represent the average flux for Hour 0-23.
Even just trying to subset I am getting a warning that reads: the variable 'Hour' appears to change size on every loop iteration (within a script). Consider preallocating for speed.
Is there no way to do this using a for loop? Ideally I don't want to use 24 lines of code just to index by Hour = 0-23.
Using MATLAB R2019a
5 个评论
Walter Roberson
2020-3-15
No, the problem is the A matrix. You find multiple entries with the same Hour value, but you try to store them in the scalar location A(i) . You could consider using a cell array
A = cell(1,24);
for i=1:24
A{i} = find(Hour == i);
end
However, considering that you are wanting to calculate average values, you should consider an approach such as
A = zeros(1,24);
for i = 1 : 24
idx = Hour == i;
A(i) = mean(flux(idx));
end
采纳的回答
Akira Agata
2020-3-15
You don't need to use for-loop.
How about the following?
load('fluxhour.mat');
[group,hourNum] = findgroups(Hour);
avgFlux = splitapply(@(x) mean(x,'omitnan'),Flux_1,group); % <- since Flux_1 contains NaN values
T = table(hourNum,avgFlux,'VariableNames',{'Hour','avgFlux'});
The output looks like:
>> T
T =
24×2 table
Hour avgFlux
____ ________
0 0.024935
1 0.024158
2 0.02483
3 0.023554
...
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!