在 matlab 实现类似 numpy.where 的功能,即按条件批量替换 tensor 的元素。
如用 isnan 判 NaN 且换掉。
numpy
import numpy as np
# 模拟 matlab:1-base,默认列向量
X = (1 + np.arange(12)).reshape(4, 3).T # 原数据
Y = X * 10 # 替换数据
index = (X % 2 == 0) # 替换条件
print("--- X:\n", X)
print("--- Y:\n", Y)
print("--- index:\n", index)
# 批量替换:满足条件换成 Y
new_X = np.where(index, Y, X)
print("--- new X:\n", new_X)
- 输出
--- X:
[[ 1 4 7 10]
[ 2 5 8 11]
[ 3 6 9 12]]
--- Y:
[[ 10 40 70 100]
[ 20 50 80 110]
[ 30 60 90 120]]
--- index:
[[False True False True]
[ True False True False]
[False True False True]]
--- new X:
[[ 1 40 7 100]
[ 20 5 80 11]
[ 3 60 9 120]]
matlab
X = reshape(1 : 12, [3, 4]); % 原数据
Y = X * 10; % 替换数据
index = (mod(X, 2) == 0); % 替换条件
fprintf("--- X:\n"), disp(X);
fprintf("--- Y:\n"), disp(Y);
fprintf("--- index:\n"), disp(index);
% 批量替换:满足条件换成 Y
X(index) = Y(index);
fprintf("--- new X:\n"), disp(X);
- 输出
--- X:
1 4 7 10
2 5 8 11
3 6 9 12
--- Y:
10 40 70 100
20 50 80 110
30 60 90 120
--- index:
0 1 0 1
1 0 1 0
0 1 0 1
--- new X:
1 40 7 100
20 5 80 11
3 60 9 120
2600

被折叠的 条评论
为什么被折叠?



