How to speed up this code?

조회 수: 12 (최근 30일)
pietro
pietro 2019년 1월 23일
답변: pietro 2019년 1월 24일
Hi all,
I have the following code that I need to speed-up:
a(1).a='a';
a(2).a='b';
a(3).a='b';
a(4).a='c';
output=(contains(cellstr(char(a.a),'b')))
the desidered output is:
output=[0 1 1 0]
In my case the size of a is [11'000x1], so the computation is pretty slow.
How can I speed up the code?
Thanks

채택된 답변

Guillaume
Guillaume 2019년 1월 23일
Your code would be much faster if you didn't so many unnecessary conversions. a.a is a comma separated list (which is bascially a cell array) which you convert to a char array and then split back into a cell array.
output = contains({a.a}, 'b')
does the same without any conversion.
It's not clear from your simple example if you really want to use contains (which check that 'b' is present anywhere within the char vector) or strcmp (which check that the char vector is exactly identical to 'b') which would be faster or even == which would be even faster but only work if all char vectors are just one character.
output = strcmp({a.a}, 'b') %faster than contains if whole string comparison is required
Other than that, there's not much option to speed this up.

추가 답변 (1개)

pietro
pietro 2019년 1월 24일
Thanks for the aswer. Now the code is really fast. I have to use contains, because I have to search for string patterns.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by