User1961
User1961

Reputation: 131

Matlab plot for many branches (piecewise function)

I want to plot the following function

I(x) = 5*(1+x/2) for -2 < x < 0
       5*(1-x/2) for  0 < x < 2
       0     elsewhere

I use the following script:

clc; close all; clear all;
L = 4;
x = -20:1:20;
I((-L/2) < x & x<0) = 5*(1 + x/(L/2));
I(0 < x & x < (L/2)) = 5*(1 - x/(L/2));
plot (x,I), grid

It does not work. Could you please help me?

Upvotes: 0

Views: 572

Answers (2)

joinhappy
joinhappy

Reputation: 31

There is one new function for piecewise function in Symbolic Math Toolbox:piecewise

so

syms x
y = piecewise(-2<x<0,5*(1+x/2),0<x<2,5*(1-x/2),0);
fplot(y)

Upvotes: 1

mpaskov
mpaskov

Reputation: 1264

You need to select which values of x to use for each condition as well. Something like this:

L = 4;
x = -5:0.1:5;
I = zeros(size(x));
cond1 = (-L/2)<x & x<0;
cond2 = 0<x & x<(L/2);
I(cond1) = 5*(1 + x(cond1)/(L/2));
I(cond2) = 5*(1 - x(cond2)/(L/2));
plot (x,I), grid

Not sure what you want to do which the boundry conditions x=0, x=-2 and x=2. But you just need to modify the cond1 and cond2.

Upvotes: 1

Related Questions