简体   繁体   English

如何在 matlab 中创建、求解和绘制条件函数

[英]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?如何在 matlab 中创建 f(x) 的函数? 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 .但是我不能给出一个v来解决f(v)并且我不能只从-41绘制f(x) 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!谢谢!

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绘制任何函数:

fplot(f, [-4, 1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM