Slow for loop string comparison

8 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 9 Mar 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));

More Answers (2)

KSSV
KSSV on 9 Mar 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.

Mathieu NOE
Mathieu NOE on 9 Mar 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.

Categories

Find more on Dates and Time in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!