其实用max和min叠加就可以实现,限制数组的最大值和最小值

1
y=min(max(x,x_min),x_max);

可以包装为函数

1
2
3
4
5
6
7
8
function y = clip(x,x_min,x_max)
arguments
x
x_min = min(x,[],'all')
x_max = max(x,[],'all')
end
y=min(max(x,x_min),x_max);
end

💡 这里用到了Matlab arguments 来给x_min和x_max 设置默认值

调用看看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>> x = reshape(1:9,3,3)'

x =

1 2 3
4 5 6
7 8 9

>> clip(x,2,7)

ans = 3×3
2 2 3
4 5 6
7 7 7