我想绘制以下函数
I(x) = 5*(1+x/2) for -2 < x < 0
5*(1-x/2) for 0 < x < 2
0 elsewhere
我使用以下脚本:
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
它不起作用。你能帮我吗?
答案 0 :(得分:1)
您还需要为每个条件选择要使用的x
值。像这样:
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
不确定您想要做什么边界条件x=0
,x=-2
和x=2
。但您只需要修改cond1
和cond2
。
答案 1 :(得分:1)
Symbolic Math Toolbox中的分段函数有一个新功能:piecewise
所以
syms x
y = piecewise(-2<x<0,5*(1+x/2),0<x<2,5*(1-x/2),0);
fplot(y)