# How to declare a function having bounds ?

42 views (last 30 days)
David Webb on 8 Feb 2015
Commented: David Webb on 9 Feb 2015
example-
f(x)= 0 x<0
x 0<x<1
-1 x>1
##### 2 CommentsShowHide 1 older comment
David Webb on 9 Feb 2015
function given above is just for example not the actual function. Just wanted to know how to declare such a function.

Matt J on 8 Feb 2015
Edited: Matt J on 8 Feb 2015
One way,
f=@(x) x.*(x>=0 & x<=1) - (x>1)
##### 2 CommentsShowHide 1 older comment
David Webb on 9 Feb 2015
Got it Thanks man !!

David Young on 9 Feb 2015
I would go for a vectorised function:
function x = clipZeroOne(x)
x(x < 0) = 0;
x(x > 1) = -1;
end
Test examples
clipZeroOne(9)
clipZeroOne(0.5)
clipZeroOne(-0.5)
clipZeroOne([-Inf -3 0 0.2 0.9 1 15 Inf]) % apply to a vector

Erik S. on 8 Feb 2015
Edited: Guillaume on 9 Feb 2015
function f=fcn(x)
if x<0
y = 0;
else if x>=0 && x<1
y = x;
else if x>1
y = -1;
end
In the example f(0) = x.
##### 2 CommentsShowHide 1 older comment
David Young on 9 Feb 2015
Edited: David Young on 9 Feb 2015
This answer has multiple issues, as they like to say on Wikipedia.
• What happens if x is exactly equal to 1?
• The output variable is f but you assign the result to y.
• "else if" isn't legal MATLAB.
• The "{} Code" button makes the code display clearly.
function y = fcn(x)
if x<0
y = 0;
elseif x<1 % it must be greater than or equal to 0
y = x;
else
y = -1; % it must be greater than or equal to 1
end
end

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!