How to plot a triangular function and other step functions in Matlab [closed]
-
21-12-2019 - |
Question
As the title indicates, I want to know how to plot a triangular function in Matlab. e.g.
f(x) = 1-|x| for |x| < 1 and f(x) = 0 otherwise
As well as the functions:
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
Solution
I assume that you are not using symbolic variables. For 2D plotting in matlab you need two equal size vectors, one per axis, so you need to create a x-axis vector and y-axis vector. In your example f(x) = 1- |x| for |x| < 1 you could do this:
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
With that you get a plot like this one:
For the other functions you have to proceed like in this one, build the x-axis vector and the y-axis vector.
UPDATE: In the other example: 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow