Avoid evaluation in vectorised conditional expressions
1 回表示 (過去 30 日間)
古いコメントを表示
Dear community,
It is well known how to vectorise for-loops that contain if-conditions, see, e.g. https://de.mathworks.com/matlabcentral/answers/17737-how-can-i-vectorize-function-with-if-statement, resulting in functions like (taken from above link):
function result = myfunc(x);
result = zeros(size(x));
idx1 = x>3;
idx2 = (x.^2 + x) > 9;
result(idx1) = 1;
result(idx2) = 2;
result(~(idx1|idx2)) = 3;
This principle works very well. However, in my case, result(idx1) and result(idx2) would be quite lengthy and expensive expressions. The problem is that both expressions are always evaluated for the entire input x, no matter if idx1 or idx2 are true or not. My question is if there is a way to avoid the evaluation of, e.g., the right hand side of result(idx2) if idx2 is false. Just as it would be in an if-elseif-construct.
I'm aware of alternative constructs with arrayfun or a "classical" for-loop with nested if-elseif-construct, but these workarounds are not efficient.
Any help is much appreciated, thank you!
0 件のコメント
採用された回答
Torsten
2023 年 1 月 31 日
移動済み: Torsten
2023 年 1 月 31 日
If your right-hand side contains expressions with x, you must replace x by x(idx1) resp. x(idx2).
2 件のコメント
Walter Roberson
2023 年 1 月 31 日
For future reference:
There are situations in which the cost of extracting a subset of data, computing with it, and expanding the results back into the appropriate locations, can exceed the savings of not performing the operation on the entire matrix.
sin() is implemented using hardware instructions. Those are potentially slower than a conditional memory move, but since the conditional move is going to need to be a loop at some level (you cannot know the relative offset without having evaluated all previous tests), sometimes it can be faster to just do the instruction and ignore or overwrite the results later. sin applied over a block of consecutive locations and be unrolled into several SIN hardware instructions in a row.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Test Scripts についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!