How do I save the output from a double for loop to a vector?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
matt beemsterboer
am 25 Apr. 2023
Kommentiert: dpb
am 26 Apr. 2023
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 Kommentare
Akzeptierte Antwort
dpb
am 25 Apr. 2023
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 Kommentare
dpb
am 26 Apr. 2023
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')
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical 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!