MATLAB 钳位函数:支持独立的上限和下限
这个简单的 MATLAB 函数将值钳位到指定的上限和下限范围内。你可以提供标量或数组作为待钳位的输入值,并用一个二元向量指定下限和上限。
clamp_function.m
function y = clamp(x, limits)
%CLAMP 将值钳位到指定范围内
% y = CLAMP(x, limits) 对输入 x 进行钳位,使结果 y
% 位于 limits(1)(下限)和 limits(2)(上限)之间。
%
% 输入:
% x - 待钳位的标量或数值数组
% limits - 二元向量 [下限 上限],指定钳位范围
%
% 输出:
% y - 钳位后的值,尺寸与 x 相同
% 验证限制范围
if numel(limits) ~= 2
error('Limits must be a 2-element vector [lower upper].');
end
lower = limits(1);
upper = limits(2);
if lower > upper
error('Lower limit must not exceed upper limit.');
end
% 执行钳位
y = min(max(x, lower), upper);
endCheck out similar posts by category:
Matlab/Simulink
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow