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?
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Michaela Jackson
le 15 Mar 2020
Commenté : Walter Roberson
le 15 Mar 2020
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 commentaires
Michaela Jackson
le 15 Mar 2020
Modifié(e) : Michaela Jackson
le 15 Mar 2020
Walter Roberson
le 15 Mar 2020
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
Réponse acceptée
Akira Agata
le 15 Mar 2020
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
...
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!