matlab按条件批量替换元素
在 matlab 实现类似 numpy.where 的功能,即按条件批量替换 tensor 的元素。如用 isnan 判 NaN 且换掉。numpyimport numpy as np# 模拟 matlab:1-base,默认列向量X = (1 + np.arange(12)).reshape(4, 3).T# 原数据Y = X * 10# 替换数据index = (X % 2 == 0)# 替换
·
在 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

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)