Plotting graphs in Octave
In this lesson, I'll explain how to create a 2D plot on Octave with some practical examples.
To follow this lesson, you should already know how to create an array. If you're not familiar with arrays, I recommend you to follow this other lesson first: Arrays in Octave.
Create an array x with a sequence of values from 1 to 6.
Type x = [ 1 2 3 4 5 6 ] in the Octave terminal and press enter.
>> x = [ 1 2 3 4 5 6 ]
x =
1 2 3 4 5 6
These numbers represent the points on the x-axis of a Cartesian graph.
Now create another array y that calculates the square of each element of the array x.
Type y = x.^2 and press enter.
>> y=x.^2
y =
1 4 9 16 25 36
These numbers are the points on the y-axis.
Now you have two arrays that combined form the (x,y) coordinates of the graph points.
To draw the graph with a line connecting the points, use the command plot(x,y) and press enter.
plot(x,y)
The first parameter is the array with the values of the variable x, while the second parameter is the array with the values of the variable y.
This command draws a 2D graph on the computer screen.
Let me give you another example.
You can also not type all the values of the arrays manually.
Use the linspace() function to create an array composed of one hundred values from 1 to 100.
x = linspace(1,100);
Now create another array y that calculates the square root of each element of the array x.
y=sqrt(x);
Both arrays are composed of 100 values.
Note. For simplicity, I added the semicolon symbol at the end of the commands. This way, I avoided displaying these long sequences of numbers on the Octave console.
Now draw the graph using the plot(x,y) function.
plot(x,y)
The output result is the graph of the square root from 1 to 100.
To color the area between the graph and the horizontal axis, use the command area(x,y) instead of plot().
area(x,y)
the area(x,y) command colors the area between the graph and the x-axis.
If this Nigiara lesson on Octave was useful, keep following us.