Equivalent of numpy.where() value choice parameters

140 views (last 30 days)
I am trying to emulate the behavior of the Numpy function numpy.where() in MATLAB, specifically the optional 2 parameters that allow picking from from other arrays.
I have the following Python code which selects
>>> import numpy as np
>>> x = np.arange(10)
>>> y = np.arange(10) * -0.1
>>> z = np.where(x % 2 == 0, x, y)
>>> print(z)
[ 0. -0.1 2. -0.3 4. -0.5 6. -0.7 8. -0.9]
The function numpy.where() selects between the two arrays, x and y, based on the condition in the first argument.
The best I have been able to do in MATLAB is:
x = 0:9
y = (0:9) * -0.1
z = zeros(size(x))
z(mod(x, 2)!=0) = y(mod(x,2)==0)
z(mod(x, 2)~=0) = y(mod(x,2)~=0)
Is there a better way of doing this?

Accepted Answer

Jan
Jan on 10 Oct 2021
Your code looks almost fine:
x = 0:9
y = (0:9) * -0.1
z = zeros(size(x));
z(mod(x, 2) == 0) = x(mod(x,2) == 0);
% ^ not ! ^ not y
z(mod(x, 2) ~= 0) = y(mod(x,2) ~= 0);
More efficient:
z = x;
m = (mod(x, 2) ~= 0);
z(m) = y(m);
  2 Comments
Andrew Glick
Andrew Glick on 11 Oct 2021
Thanks!
(I'm a bit embarrassed that I made two obvious typos in the Matlab code. Oops! Thanks for catching those!)
Jan
Jan on 13 Oct 2021
Typos are then beloved companion of the programmer. They emerge from expressing thoughts by fingers. As soon as we omit the keyboards by developping a mind controlled input method, the new device will get a bi-directional interface and monopolistic internet services will project commercials directly in my subconciousness. Therefore I like typos.

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!