如何在 Matlab 中绘制三角函数和其他阶跃函数 [关闭]
-
21-12-2019 - |
题
正如标题所示,我想知道如何在Matlab中绘制三角函数。例如
f(x) = 1-|x| for |x| < 1 and f(x) = 0 otherwise
以及功能:
Af(x) = A for x >= 0 and Af(x) = 0 for x < 0; -f(x) = -1 for x >= 0 and -f(x) = 0 for x < 0
解决方案
我假设您没有使用符号变量。对于 matlab 中的 2D 绘图,您需要两个大小相等的向量,每个轴一个,因此您需要创建一个 x 轴向量和 y 轴向量。在您的示例中,f(x)= 1- | x | | x | <1您可以做到这一点:
x = linspace(-5,5,500); %x-axis vector from -5 to 5 with 500 points
y = zeros(1,500); %y-axis vector initialized to 0, also 500 points like the x-axis vector
y(abs(x) < 1) = 1- abs(x(abs(x)<1)); %the points corresponding to |x|< 1 are set to |x|
figure() %new figure
plot(x,y) %plot
box off %removing box
grid on %adding grid
xlabel('x axis', 'FontSize', 15) %label of x axis
ylabel('y axis', 'FontSize', 15) %label of y axis
axis([x(1), x(end), -0.5, 1.5]) %axis limits
这样你就得到了像这样的情节:
对于其他函数,您必须像本函数一样继续,构建 x 轴向量和 y 轴向量。
更新: 在另一个例子中: f(x) = A for x >= 0 and f(x) = 0 for x < 0
:
A = 3;
x = linspace(-5,5,500); %x-axis vector from -5 to 5 with 500 points
y = zeros(1,500); %y-axis vector initialized to 0, also 500 points like the x-axis vector
y(x >= 0) = A; %the points corresponding to x >= 0 are set to A
figure() %new figure
plot(x,y) %plot
box off %removing box
grid on %adding grid
xlabel('x axis', 'FontSize', 15) %label of x axis
ylabel('y axis', 'FontSize', 15) %label of y axis
axis([x(1), x(end), -0.5, 3.5]) %axis limits
不隶属于 StackOverflow