How do I save the output from a double for loop to a vector?
6 次查看(过去 30 天)
显示 更早的评论
Hi all,
I am trying to use a double for loop to count the number of patients admitted to a hospital (from a data set in excel) during each of the 24 hours in a day. I believe that the for loops are correct but I am unsure as to how I save the outputs (number of patients admitted each hour) in a vector?
counter = 0;
for n = 0:23
for i = 1:height(Exceldata)
if (duration(n,0,0) <= NUM_Time_Data(i)) & (NUM_Time_Data(i) <= duration(n,59,0))
counter = counter + 1;
end
end
VectorOfValues(n) = counter;
end
0 个评论
采纳的回答
dpb
2023-4-25
counter = 0;
VectorOfValues=zeros(24,1); % preallocate
for n = 0:23
for i = 1:height(Exceldata)
if (duration(n,0,0) <= NUM_Time_Data(i)) & (NUM_Time_Data(i) <= duration(n,59,0))
counter = counter + 1;
end
end
VectorOfValues(n+1) = counter;
end
But, "the MATLAB way" to do this will eliminate both loops -- use histcounts or, better yet, put the Excel data into a Matlab table and use groupsummary with the time data turned into datetime or timeofday class. See the general doc on tables and processing by grouping variables; it'll be a big timesaver in the long run compared to going at it brute force for every little detail.
2 个评论
dpb
2023-4-26
Still, it would be far better to load the data into a more useful form for analyses...
tPatients=table(datetime(2020,randi([1 12],1000,1),randi([0 23],1000,1)), ...
hours(randi([0 23],1000,1))+minutes(randi([0 59],1000,1)), ...
'VariableNames',{'AdmittingDate','AdmittingTime'});
tPatients=sortrows(tPatients,{'AdmittingDate','AdmittingTime'});
tPatients.AdmittingTime.Format='hh:mm';
head(tPatients)
groupcounts(tPatients,'AdmittingTime','hour')
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!