How can I run these codes in a for loop?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2023-2-28
编辑:Voss
2023-2-28
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 个评论
Voss
2023-2-28
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
2023-3-13
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!