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!