Slow for loop string comparison
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sebastian Engelsgaard
el 9 de Mzo. de 2021
Respondida: Mathieu NOE
el 9 de Mzo. de 2021
Hi,
I have a for loop which detects the exact position of a specific string in the 'Time' row of a timetable, however it is really slow... anybody with ideas to speed up this process? My code is shown below, and the Time elements format is, e.g. 30-Sep-2019 08:58:08.000
for j=1:500001
app.v = string(app.ttable.Time(j));
if app.v==string('30-Sep-2019 08:58:08.000')
app.SelectfileDropDown.Items = string(app.ttable.Time(j));
end
end
0 comentarios
Respuesta aceptada
Stephen23
el 9 de Mzo. de 2021
I assume that
app.ttable.Time
is actually a datetime array. In that case, your loop very inefficiently converts each datetime individually to a string, and then compares that string against some characters. A much more efficient approach would be to use MATLAB indexing:
d = datetime(2019,9,30,8,58,8) % 30-Sep-2019 08:58:08.000
X = d==app.ttable.Time;
app.SelectfileDropDown.Items = string(app.ttable.Time(X));
0 comentarios
Más respuestas (2)
KSSV
el 9 de Mzo. de 2021
Obviously what you have shown will be dead slow and also may not work.
You can striaght aways use strcmp, contains. Read about them. Aslo you need not to convert the date into string, rather you can have them into Datetime class and striaght away work on them.
0 comentarios
Mathieu NOE
el 9 de Mzo. de 2021
hello
for / if loops will make this very slow
here my suggestion / demo code for faster method :
t1 = datetime(2000,11,1,8,0,0);
t2 = datetime(2020,11,5,8,0,0);
t = (t1:t2)';
%% 1st method
tic
for j=1:numel(t)
if string(t(j)) == string('08-Feb-2001 08:00:00')
disp(' found')
end
end
toc
% Elapsed time is 6.430877 seconds.
%% 2nd method
tic
n = datenum(t); % list of dates
test_date = datenum('08-Feb-2001 08:00:00'); % test date
ind = find(n == test_date);
date_found = t(ind)
toc
% Elapsed time is 0.036663 seconds.
0 comentarios
Ver también
Categorías
Más información sobre Dates and Time en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!