SwordW
SwordW

Reputation: 610

How to create, solve and plot conditional function in matlab

For example, I have a

f(x)=
    9+4(x+3), if -4<=x<-1 (subf1)
    7-9(x-0.4), if -1<=x<1 (subf2)

How can I create a function of f(x) in matlab? I tried

f=0
syms x
f=f+ subf1 with heaviside+ subf2 with heaviside

But I cannot give a v to solve f(v) and I cannot plot f(x) only from -4 to 1. So is there another way to write conditional function?

Sorry my description is a little hard to follow. If you don't understand what I am asking, please let me know and I will try to rephrase. Thank you!

Upvotes: 1

Views: 689

Answers (1)

Erfan
Erfan

Reputation: 1927

Depends on what you want to do with it. If for some reason you need symbolic, here is one way to write your symbolic function:

syms x
f1 = (9 + 4 * (x + 3)) * heaviside(x + 4) * (1 - heaviside(x + 1));
f2 = (7 - 9 * (x - 0.4)) * heaviside(x + 1) * (1 - heaviside(x - 1));
f = symfun(f1 + f2, x);

Otherwise, you can write your function in a file as:

function out = f(x)
out = (9 + 4 * (x + 3))*(x>=-4)*(x<-1) + (7 - 9 * (x - 0.4))*(x>=-1)*(x<1);

Or you can define it as an anonymous function:

f = @(x) (9 + 4 * (x + 3))*(x>=-4)*(x<-1) + (7 - 9 * (x - 0.4))*(x>=-1)*(x<1);

Then, you can plot any of the functions using, for instance, fplot:

fplot(f, [-4, 1])

Upvotes: 1

Related Questions