How can I run these codes in a for loop?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ashfaq Ahmed
am 28 Feb. 2023
Kommentiert: Campion Loong
am 13 Mär. 2023
Hi! I understand that the variables should not be named dynamically. So, I would like to have an idea on how can I run these kind of code in a for loop without repeating the variable inthe future. A good idea will help me to think differently and more efficiently. Thank you in advance!!
idx_0 = hour(result.HourSeries1)==00;
m0 = mean(Climatology1.H1(idx_0,:))
idx_1 = hour(result.HourSeries1)==01;
m1 = mean(Climatology1.H1(idx_1,:))
idx_2 = hour(result.HourSeries1)==02;
m2 = mean(Climatology1.H1(idx_2,:))
idx_3 = hour(result.HourSeries1)==03;
m3 = mean(Climatology1.H1(idx_3,:))
idx_4 = hour(result.HourSeries1)==04;
m4 = mean(Climatology1.H1(idx_4,:))
I tried to do this way but it shows "Array indices must be positive integers or logical values."
x = [0:23];
for i =1:24;
idx{i-1} = hour(result.HourSeries1)==i-1;
m{i-1} = mean(Climatology1.H1(idx{i-1},:))
end
0 Kommentare
Akzeptierte Antwort
Voss
am 28 Feb. 2023
Bearbeitet: Voss
am 28 Feb. 2023
If the means are all scalars
m = zeros(5,1);
for ii = 1:5
idx = hour(result.HourSeries1) == ii-1;
m(ii) = mean(Climatology1.H1(idx,:));
end
Otherwise
m = zeros(5,size(Climatology1.H1,2));
for ii = 1:5
idx = hour(result.HourSeries1) == ii-1;
m(ii,:) = mean(Climatology1.H1(idx,:), 1);
end
3 Kommentare
Voss
am 28 Feb. 2023
The built-in hour function returns a double, so I assume the hour you're using is your own function or variable.
idx = strcmp(hour(result.HourSeries1),sprintf('%02d',ii-1))
Campion Loong
am 13 Mär. 2023
Adding to @Voss's answer, this is basically subscripting with "hour" in result.HourSeries1. Depending on whether that is a datetime or text, I would prefer holding the "Climatology" data in a timetable or table so your data labels (i.e. time, text) go with your data, like this (if you use datetime)
% Making up random multi-column data for H1
ResultTimes = datetime(2023,3,13) + hours(1:1000)';
Climatology = timetable(ResultTimes, rand(1000,5),'VariableNames',"H1")
% Pull out data based on time-of-day (e.g. 3AM)
Climatology( hour(Climatology.ResultTimes) == 3, :).H1
% Now applying @Voss's answer for non-scalar means
m = zeros(24,size(Climatology.H1,2));
ResultTimes_HourOfDay = hour(Climatology.ResultTimes);
for ii = 1:24 % note HoD ranges from 0-23
m(ii,:) = mean( Climatology(ResultTimes_HourOfDay == ii-1,:).H1 );
end
m
Siehe auch
Kategorien
Mehr zu Data Type Conversion 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!