Equivalent of numpy.where() value choice parameters

62 次查看(过去 30 天)
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?

采纳的回答

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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by