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?
0 个评论
采纳的回答
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 个评论
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 Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!