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 Ansichten (letzte 30 Tage)
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 Kommentare
Michaela Jackson
Michaela Jackson am 15 Mär. 2020
Bearbeitet: Michaela Jackson am 15 Mär. 2020
Perhaps I am just not understanding this at all.
A = zeros(1,24);
for i=1:24
A(i) = find(Hour == i);
end
Now I am getting: Unable to perform assignment because the left and right sides have a different number of elements.
I guess that means I can't store a vector using A(i)?
Walter Roberson
Walter Roberson am 15 Mär. 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Akira Agata
Akira Agata am 15 Mär. 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
...

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by