How do I save the output from a double for loop to a vector?
7 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
dpb
il 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 Commenti
dpb
il 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')
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!