Generating piecewise function and plotting it

237 views (last 30 days)
ÖMER FARUK KURANLI
ÖMER FARUK KURANLI on 20 Mar 2018
Edited: Rohit Sinha on 4 Apr 2022
Hi! I'm very new for Matlab at the moment. I tried the solve these piecewise equations by vectorized way. But for the condition one, I get error beacause of putting insufficient argument. I need help and waiting your solutions. here is my solution ;
function y=piecewise(x)
%ilk şart first cond
x1=x(x<-1)
y(x<-1)=-1
%ikinci şart second cond
x2=x(-1<=x & x<2);
y(-1<=x & x<2)=x2.^2+x;
%ücüncü şart third cond
x3=x(2<=x & x<4)
y(2<=x & x<4)=-x3+2
%dördüncü şart fourth cond
x4=x(4<=x & x<6)
y(4<=x & x<6)=x4.^3+2*x.^2-3
%besinci şart fifth cond
x5=x(6<=x)
y(6<=x)=2*exp(0.1*x5-0.6)
x=-5:0.1:10
y=piecewise(x)
plot(x,y)

Answers (3)

Amjad Green
Amjad Green on 20 Mar 2018
can you write the entire question in english
  7 Comments
john Snori
john Snori on 1 Sep 2021
We can implement piecewise functions by:
  • Treating each function separately and merge and plot them on the same graph
  • If-else statement along with for-loop
  • Switch-case statement
  • Using built-in function of Matlab which returns the piecewise function using a single-line command.

Sign in to comment.


Star Strider
Star Strider on 20 Mar 2018
I always use ‘logical indexing’ for these problems.
This should do what you want:
f = @(x) (-1).*((x < -1)) + (x.^2+x).*((-1 <= x) & (x < 2)) + (x+2).*((2 <= x) & (x < 4)) + (x.^3+2*x.^2-3).*((4 <= x) & (x < 6)) + (2*exp(0.1*x-0.6)).*((6 <= x));
x = linspace(-5, 10, 500);
figure(1)
plot(x, f(x))
grid
  1 Comment
Christopher Creutzig
Christopher Creutzig on 20 Apr 2018

I'm not sure I would call that “logical indexing,” since you are not actually indexing. But I haven't checked if there is an official lingo rule covering this case, so I may be completely wrong.

In some cases, for some users, code like the above may not be the form they want to read. (Also, it fails if any of the subexpressions returns NaN or Inf.)

Just for variety, here is another version (which definitely uses “logical indexing”):

function y = f(x)
  % set default
  y = nan(size(x));
  y(x < -1) = -1;
    ind = (-1 <= x) & (x < 2);
    y(ind) = x(ind).^2 + x(ind);
    ind = (2 <= x) & (x < 4);
    y(ind) = x(ind) + 2;
    ind = (4 <= x) & (x < 6);
    y(ind) = x(ind).^3 + x(ind).^2 - 3;
    ind = x >= 6;
    y(ind) = exp(0.1*(x(ind)-6));
  end

With this, you can then use linspace and plot or simply call fplot:

fplot(@f,[-5,10])

Sign in to comment.


Rohit Sinha
Rohit Sinha on 4 Apr 2022
Edited: Walter Roberson on 5 Apr 2022
You could try this method
syms x %makes x a symbolic variable
f= piecewise(x<-1, -1, x>=-1 & x<2, x^2+x, x>=2 & x<4, -x+2, x>=4 & x<6, x^3+2*x^2-3, x>=6, 2*exp(0.3*(x-6))); %makes a piecewise function for given conditions
fplot(f) %plots the piecewise function

Community Treasure Hunt

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

Start Hunting!

Translated by