Slow for loop string comparison
조회 수: 8 (최근 30일)
이전 댓글 표시
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
채택된 답변
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));
댓글 수: 0
추가 답변 (2개)
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.
댓글 수: 0
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!