When data is gathered, visualizing it is almost always a handy way to find any abnormalities or trends in the data. In MATLAB, there are many different ways to visualize data, but here is one: the plot() function. Let's get started to find out how to use it!
Let's start out by defining a range of x in the form of a vector and an anonymous function to calculate with the x vector; after that, the plot function can be used to graph the relationship between x and the anonymous function's output.
matlab
x = linspace(0,4,50);
g = @(x) cos(x) + x.^2 - x + 2;
clf
plot(x,g(x))
In the code above, x was defined from 0 to 4 with 50 evenly-spaced values between and including the bounds. Then an anonymous function, g, was defined to take in some x values. We then used the plot() function with the first input being the x input and the second input being the y values, or the output of the function g.
The color of the graphed line can also be changed by using a color value such as 'r' for red, 'k' for black, and 'b' for blue.
matlab
plot(x,g(x),'b')
By adding the 'b' as the third input, it will change the color of the graph line to be blue.
Let's say we wanted to label the axis and title of the plot, then how would we do that? Let's see:
matlab
title("x and g(x) Relationship");
xlabel("x axis");
ylabel("y axis");
By adding these labels, they will add a title, x-axis label, and y-axis label, respectively, to the graph.
If we wanted to graph two lines instead, we could modify our code like below:
matlab
% from before
x = linspace(0,4,50);
g = @(x) cos(x) + x.^2 - x + 2;
f = @(x) x.^3 - 3*x;
clf
plot(x,g(x),'r',x,f(x),'b')
In the code above, we defined two anonymous functions: f and g. Both of which were plotted using the plot() function and each will have different colored lines because we used two different color labels, 'r' and 'b'. Now what if we wanted to label the lines to tell them apart? Then we could use the legend property of a plot to differentiate the two lines.
matlab
legend("g(x)","f(x)",'Location','Southwest');
In the code snippet above, the first inputs to the legend call were the names of the lines, "g(x)" and "f(x)". The last two inputs were to define where the legend would go; MATLAB like to use cardinal directions for defining this.
Now we can plot our data to 2D plots!