Slow for loop string comparison

조회 수: 8 (최근 30일)
Sebastian Engelsgaard
Sebastian Engelsgaard 2021년 3월 9일
답변: Mathieu NOE 2021년 3월 9일
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

채택된 답변

Stephen23
Stephen23 2021년 3월 9일
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));

추가 답변 (2개)

KSSV
KSSV 2021년 3월 9일
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 2021년 3월 9일
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.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by