Matlab clamping function with separate upper & lower limits
This simple Matlab function clamps a value to lie within specified upper and lower limits. You can provide a scalar or array of values to be clamped, along with a two-element vector specifying the lower and upper bounds.
function y = clamp(x, limits)
%CLAMP Clamp a value to lie within specified limits
% y = CLAMP(x, limits) clamps the input x so that the result y
% lies between limits(1) (lower bound) and limits(2) (upper bound).
%
% Inputs:
% x - scalar or array of numeric values to clamp
% limits - 2-element vector [lower upper] specifying clamp range
%
% Output:
% y - clamped values, same size as x
% Validate limits
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
% Perform clamping
y = min(max(x, lower), upper);
end
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow