Author
Keywords
Programming, Code optimisation, Matlab
Review Status
Unreviewed
Motivation
There are many applications where one wishes to replace negative (or postive) elements of a vector (the method is applicable to both) with zeros. An example may be the computation of partial moments of a random variable. This Tip explains how this can be done in vectorised form.
How to do it
Assume one has a vector $x$ where one wishes to replace all negative elements by zero. The straightforward way in Matlab would be
x(x<0) = 0;
However, this requires Matlab to compute the logical vector $x < 0$, which is costly, especially for large vectors. The same can be achieved by the command
x = (x + abs(x)) / 2;
To replace positive values by 0, the computation is
x = (x - abs(x)) / 2;
Please note that if one intends to sum over the resulting vector (as is the case when one computes partial moments), one should of course first sum, then divide by 2.
Internal Links
Concepts |
… |
Tutorials |
Tips |
… |
Related Articles |
… |
External links
References |
1. Gilli, M., D. Maringer and E. Schumann. (2011). Numerical Methods and Optimization in Finance. Elsevier.
|
Weblinks |
… |