How do I define a piecewise function and then use it in a file function?

15 views (last 30 days)
Hello all, I need to define a step function. This function is f = x for x<0 and f = x^2 + 1 for x => 0. My question is how do I define this as a function file such that I can then use this function as an input on a larger function file whose inputs determine what x is?

Answers (2)

Star Strider
Star Strider on 22 Sep 2016
Edited: Star Strider on 22 Sep 2016
One approach (with demonstration code and plot):
t = linspace(-2, 2);
sqrstep = @(x) x.*(x < 0) + (x.^2 + 1).*(x >= 0);
figure(1)
plot(t, sqrstep(t))
grid
EDIT To create a function file version:
function y = sqrstep(x)
y = x.*(x < 0) + (x.^2 + 1).*(x >= 0);
end
Then save it as ‘sqrstep.m’ (or whatever name you want to call it, so long as the function name and file name match).

Walter Roberson
Walter Roberson on 22 Sep 2016
MATLAB is not as convenient as one might hope for defining piecewise functions.
The code that Star Strider shows in his answer is a good use of logical indexing, along with a small numeric trick to splice the cases together. Unfortunately, that code will break down if any of the values produced by any of the sub-expressions are +/- inf or nan . For example,
F = @(x) (x == 0) .* 1000 + (x ~= 0) .* 1./x
the intent of this code is a function that produces 1/x for non-zero x and produces 1000 at 0. But
>> F(-1:1)
ans =
-1 NaN 1
The 1/x still gets evaluated at x == 0, producing inf, and that (x ~= 0) being false at 0 produces 0 (false) leading o 0 * inf with the intention that the inf be zeroed out -- but 0 * inf is NaN and that NaN "pollutes" the rest of the expression at that point -- the 1000 + NaN produced for x == 0 gives NaN .
You can see from this that it is not a true piecewise, and the idiom breaks sometimes.
There is a piecewise() buried in the symbolic engine of the Symbolic Toolbox, but unfortunately there is no MATLAB interface to it, and accessing it through feval(symengine) is tricky, so the easiest way to use it is to do a full evalin(symengine) :
G = evalin(symengine, 'piecewise([x = 0, 1000], [x ~= 0, 1/x])');
subs(G, [-1 0 1])
This is a true piecewise, but it is not at all convenient to use from the MATLAB level -- and of course gives you a symbolic expression rather than something you can use numerically. And you cannot use matlabFunction() to convert this symbolic piecewise into a function handle. :(

Community Treasure Hunt

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

Start Hunting!