Learn how to use Octave shell, program basic Octave scripts, functions, packages and much more…
GNU Octave is a project started by James Rawlings and John Ekerdt, but its main developer is John Eaton, with the name inspired by the chemist Octave Levenspiel.
Octave is able to solve many different problems using its native functionalities and can be extended using its programming language, the code being executed line-by-line every time you run an Octave program. Octave also features some handy plotting capabilities that we cover later in this tutorial, although it’s worth bearing in mind that Octave’s main purpose is for performing mathematical and numerical computations – it is not a replacement for general-purpose programming languages such as C, Objective-C or C++.
Although Octave tries to be as compatible as possible with MATLAB, there are infrequent cases that you cannot directly execute Octave code in MATLAB and vice-versa. We’re going to walk you through the process of installing Octave, using the Octave shell and writing functions, scripts and Octave packages – let’s get started!
Step 01 Install Octave
On a Debian 7 system you can install Octave simply by executing the following command as root:
# apt-get install Octave
After installing Octave, you can run the following command to find out its version:
$ octave -v GNU Octave, version 3.6.2
Although Octave has many packages that extend its capabilities, most of them are not installed by default and you may find that you need to install them manually.
Step 02 The Octave shell
As is the case with many mathematical packages, Octave uses its own shell for interacting with the user. The Octave command prompt is pretty simplistic and does not offer much information. You can type ‘help’ for more information. The shell allows you to make simple calculations easily but also allows you to create variables and use their values:
octave:5> lud = 2 lud= 2 octave:6> lud lud= 2 octave:7> LUD error: `LUD' undefined near line 7 column 1
The last error message shows that Octave is case sensitive because it cannot recognise a variable named “LUD”.
Step 03 Interact with the Octave shell
Octave also supports complex numbers. If you are good at mathematics you should remember that complex numbers have a real part and an imaginary part and can be written in the ‘a + b * i’ format, where i is the square root of -1. After defining some complex numbers, you can then add, subtract, divide, multiply them, and so on.
Step 04 Octave variables
If you want to see the existing variables, you should execute the whos command. In order to delete a variable, you may use the clear <variable name> command. Be very careful with the clear command as it works with the wildcard *. For example, in order to delete all variables that start with w, you should run the following command:
octave:13> clear w*
If you want to delete all active variables at once, just type clear.
Step 05 Doing basic calculations with the Octave shell
Octave supports most of the usual mathematical functions and allows you to use them when performing calculations. For example, the power() function can be used as follows:
octave:15> power(2,10) ans = 1024
You can even evaluate a function (poly) for a range of values (y). This can happen as follows:
octave:12> y = [1:1:10] octave:13> poly = [1 2 2] octave:14> polyval(poly,y)
You can also create random numbers with the rand() function. The following command creates a 2×2 matrix with random numbers:
Step 06 Octave arrays and polynomials
Octave also supports polynomials of any type. You can create a polynomial as follows:
octave:2> poly = [1 5 -2]
This creates a polynomial named poly (poly is also an array) that equals to “x^2 + 5 x – 2”.
Using the roots command, you can find the roots of a polynomial. In order to evaluate a polynomial poly for a given value (eg x=5), you should use the polyval function as follows:
octave:5> polyval(poly, 5)
Step 07 Program in Octave
Octave allows you to program your own functions and packages, which is especially practical when you want to execute the same commands many times. You can even interact with the user, asking them for input. If you want to see the list of the currently installed packages, you should type the command:
octave:3> pkg list
Step 08 Octave functions
Octave functions can use all the common statements that can be found in most programming languages. As an example, you can check if a variable n is a string by using the following code:
if ( ischar(n) ) usage("Input must be an Integer number"); endif
In order to use a function stored in a file, you do not have to manually load the file inside Octave; all you have to do is to be inside the directory where the source code of the function is and type the name of the file that contains the function.
Step 09 Program Fibonacci numbers
Provided that the implementation file of the function, called myFib.m, is located in your current working directory, you can call the myFib() function as follows. The Fibonacci function is a recursive function because it calls itself.
octave:1> myFib(4) ans= 3 octave:2> myFib(5) ans= 5 octave:3> myFib(20) ans = 6765 octave:4> myFib(30) ans = 832040 octave:5>
Step 10 Program the Factorial function
Similar to the myFib function, you can use the myFactorial function as follows:
ans = 120
octave:6> help myFactorial
‘myFactorial’ is a function from the file /home/mtsouk/docs/article/working/Octave.LUD/code/myFactorial.m
Wednesday 23 April 2014
A function for calculating the factorial of a number
Step 11 Octave packages
GNU Octave also supports packages programmed by others that extend its capabilities. If you want to see the list of the currently installed packages, you should type the following Octave command:
octave:1> pkg list
If you want to find more information about an installed package, use the pkg describe <package name> command.
You can load and unload packages using the following commands:
octave:8> pkg load benchmark octave:9> pkg unload benchmark
Step 12 Put the two functions in a package
In order to better organise your code and functions and be able to offer your work to others, Octave allows you to put your code into Packages. Although creating a package is more difficult than creating a simple function, the actual code of each function does not need to change. You will first need a directory in which to put your files (LUD). Inside the directory, you have to have a file called DESCRIPTION and a file called COPYING. Optionally, you can have a file called INDEX. You will also need to have a directory called inst. The presence of the inst directory may be optional but if you are going to have any .m files in your package, you will need it, which makes it almost mandatory. When every file is ready, you need to run the following command from the command line to create an archive of the package:
$ tar zcvf lud.tar.gz LUD/
You then you have to run the following command from the Octave shell in order to create the actual Octave package:
octave:1> pkg build ./ lud.tar.gz skipping line
The last command generates a new file called lud-0.1.0.tar.gz, which is the distribution file for the Octave package. To install the package on your machine, you will need to run Octave as the root user because you are going to write files inside the /usr/share/octave directory and execute the following command from the Octave shell:
octave:2> pkg install lud-0.1.0.tar.gz
Having loaded the LUD package, you can call the two functions of the LUD package without having their implementation in your current working directory.
Step 13 Octave scripts
The presented Octave script asks the user to type in two integer numbers. Then it creates a matrix with random numbers and prints the minimum and the maximum values that can be found in the matrix.
You have to save the script as a file that has the .m extension for Octave to understand it. If you save it as myscript.m and you run Octave from the directory of the script you can call it as follows:
octave:1> myscript Give me the number of rows: 2 Give me the number of columns: 3 The minimum value found is: 0.13466 The maximum value found is: 0.95593 octave:2>
Step 14 Plot using Octave
The plotting capabilities of Octave are impressive. Given a polynomial c, you can easily plot it using the plot() command as follows:
octave:4> c = [1 -1 2 -3] c= 1 -1 2 -3 octave:5> plot(c)
The aforementioned command creates a very simplistic output because Octave just calculates the polynomial’s values for 1, -1, 2 and -3 and then connects the four points. To get a more accurate output, Octave has to draw and connect more points. It would also be very useful to be able to define the limit values of the x-axis. The following commands do what you want:
octave:1> c = [1 -1 2 -3] c= 1 -1 2 -3 octave:2> myVals = linspace (0, 5, 100); octave:3> y = polyval(c, myVals); octave:4> plot(myVals, y);
All the work is done by the linspace (0, 5, 100); command, which divides the [0,5] space into 100 points. It then connects all 100 points, creating a more pleasant output.
Step 15 Advanced plotting examples
This step will create a graph and improve its output step by step using Octave. First, the usual commands from the previous step must be executed:
octave:3> c = [1 -1 2 -3]; octave:4> myVals = linspace (0, 5, 100); octave:5> y = polyval(c, myVals);
The next command changes the width of the line that is going to be sketched:
octave:6> plot(myVals, y, "linewidth", 3);
The command below displays the “f(x)” string on the y-axis:
octave:7> set(gca, "ylabel", text ("string", "f(x)", "fontsize", 25))
The following command adds a beautiful grid to the output:
octave:8> grid on
The next command draws a legend on the output:
octave:9> legend("Linux User and Developer");
Step 16 Output formats
After executing all the commands of the previous step, you might like to save the output to a file. The following command will do the job:
octave:10> print("LUD.png", "-dpng");
The last command saves the output graphics in PNG format using the ‘LUD.png’ filename. Other supported formats include Encapsulated PostScript (eps), PostScript (ps), PDF (pdf), JPEG (jpg or jpeg), GIF (gif), TeX picture (tex) and LaTeX picture (pslatex).