Avoid evaluation in vectorised conditional expressions
Mostrar comentarios más antiguos
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!
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Performance and Memory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!