Equivalent of numpy.where() value choice parameters

153 visualizaciones (últimos 30 días)
Andrew Glick
Andrew Glick el 10 de Oct. de 2021
Comentada: Jan el 13 de Oct. de 2021
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?

Respuesta aceptada

Jan
Jan el 10 de Oct. de 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 comentarios
Andrew Glick
Andrew Glick el 11 de Oct. de 2021
Thanks!
(I'm a bit embarrassed that I made two obvious typos in the Matlab code. Oops! Thanks for catching those!)
Jan
Jan el 13 de Oct. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by