Time consumption of string copied to string array

I programmed a simulation and currently optimizing the function in terms of time. Therefore I use the profiler to check the time consumption per function. Here I was wondering, why a simple copy instruction of a string into a string array - that is indeed often called - takes nearly 10% of simulation time:
in line 65 you can see the instruction. ‘obj.dataList’ is a string-array, ‘pos’ a logical array with equal size of ‘obj.dataList’ and only a single true value and ‘value’ a string. I do not know what exactly happens "inside" of Matlab; since I am using strings, there has to be some kind of repeating memory allocation which of course takes time. But that this single line takes 10% of simulation time, seems a bit long.
Does anyone have an idea, how I can optimize that?

 採用された回答

Matt J
Matt J 2022 年 5 月 8 日

0 投票

pos a scalar between 1 and the length of obj.dataList and value a string.
That is definitely not the case. In the preceding line, you can see that pos is the result of a logical operation, and therefore is an array consisting of logical zeros and ones.

5 件のコメント

Thomas Cimiega
Thomas Cimiega 2022 年 5 月 8 日
Yes you are right! Sorry for that. I'll correct that. But anyways: It is guaranteed that only one entry of ‘pos’ is ‘true’ and no increment of ‘obj.dataList’s size happens.
Matt J
Matt J 2022 年 5 月 8 日
編集済み: Matt J 2022 年 5 月 8 日
Even so, it is an O(N) vector operation, not a scalar operation. The code has no way of knowing that only one entry of pos is true. Even if it did, it does not know which one of them is true. It must therefore search through all of them.
Matt J
Matt J 2022 年 5 月 8 日
This might be faster,
pos=find(pos,1);
if ~isempty(pos)
obj.dataList(pos)=value;
end
Thomas Cimiega
Thomas Cimiega 2022 年 5 月 8 日
Thank you. Yes I also thought of mapping the correct indices initially and setting 'pos' according to that instead of using a binary array. I will try this and solve the thread, if it works.
Thomas Cimiega
Thomas Cimiega 2022 年 5 月 9 日
Your approach using
pos=find(pos,1);
if ~isempty(pos)
obj.dataList(pos)=value;
end
reduced the processing time by half, thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by