This workshop is about the multi OS, command-line, high level, numerical mathematics program, called Octave.

Last change: 26.01.2012.

- Introduction
- First Steps
- Basic Examples
- Variables
- Matrices and Vectors
- Polynomials
- Differential Math
- Integral Math
- Saving sessions
- Further Features - an outlook
- Last Word and Thanks
- Appendix A: Octave Mini Reference

Octave is a high-level interactive language for numerical computations. It provides a convenient command line interface for solving linear and nonlinear problems numerically.

In simpler words Octave is a very sophisticated scientific calculator. You could compare it to Matlab, R, which had been demonstrated here in the last two years, or Maple.

Octave is free software released under the GNU General Public License (GPL), you should have received a copy of this license with your version of GNU Octave. If not please take a look at the GNU GPL website. This means, that you can download, use, modify and redistribute Octave free of charge, as long as you include original copyright notices. Usage is not restricted to non-commercial contexts. Please read the GPL, if you have more questions about legal issues.

System requirements for Octave are low, since it only uses a command line interface. You need approximately 200MB - less if no debugging is compiled in - of disk-space. Memory and CPU usage depend largely on the problems you wish to solve. Clearly working with huge amounts of data will need lots of RAM and solving complicated problems will need a fast CPU, if you don't want it to take all day.

Octave can run under Linux, which is very easy, because the command line doesn't need any graphics, not even to start it and braille support works flawlessly. But Octave also works on Windows, Mac OS X and Solaris. Binary packages - i.e. programs ready to run - can be found from the octave download page.

This document is structured into comprehensive sections, which can all be reached from the table of contents at the top of this document.

Each section has a link underneath it to bring you back to the top of the document, i.e. the table of contents.

Each Octave example will be shown including its prompt. So to type the examples yourself, please omit the displayed octave prompt and only enter the command. An Octave prompt always ends with a greater than sign (>). For example like this:

octave:1>

This document is copyright © 2011-2012 Julien Claassen. You are welcome to redistribute it and use it in non-commercial context, under the conditions, that this copyright is present and no fee is charged for the document itself. Charges for material and postage are acceptable, if you plan to distribute this document in printed form or on removable media.

On Linux - or wherever you have a command line - it is very easy. You just type:

`octave`

On Windows: if you installed it correctly from Octave Forge Windows, then:

- Go to start menu
- Click "all programs"
- GNU Octave
- Octave

This should start the Octave command line.

Now Octave displays a short message and shows you a prompt like this:

`octave:1>`

That's the point where you can start typing octave commands. A command is always confirmed (finished) by pressing the ENTER/RETURN key. Never forget that! After you typed your command and want Octave to do something: press ENTER!

One of the most important things is always to get help. You can get help in a few ways. The easiest is:

`octave:1> help`

Which shows you a simple message on how to get more detailed help.

help <name> - This will give you a short and simple help for the function, keyword or operator called "name".

You can also access the complete documentation. This requires the GNU info program. Info is a documentation browser. The doc command can work just as easily:

doc - This will open the Octave documentation at the first page.

doc <name> - This will open the documentation at the place where "name" is documented. This can be much more detailed than help.

Then you have lookfor. Lookfor searches the help text of all currently available function files.

lookfor <word> - This will look for "word" in the first sentence of every help entry.

lookfor --all <word> - This will look for "word" in the complete help text.

All forms of lookfor can take some time, so only use them, if you are _**really desperate**_.

On the Octave prompt type:

`octave:2> quit`

or

`octave:2> exit`

If you need to interrupt Octave, while it's doing something press control+c. This should interrupt it immediately and get you back to the Octave prompt.

Octave can solve problems from the most primitive pocket calculator tasks to highly complex and scientific calculations. We will start with the pocket calculator.

First of all, we might wish to see as many digits as possible, so we set Octave to display its "long format":

`octave:1> format long`

Octave knows about all the simple operators like +, -, /, * and ^ (caret) exponentiation. (Note: caret on a German keyboard can be found left from 1, it will only show after entering the next character, for it is an accent. On American keyboards it is shift+6).

```
octave:2> 3 + 7
```

ans = 10

octave:3> 5 * 6

ans = 30

octave:4> 12 / 3

ans = 4

octave:5> 2 -3 * 4 +6 / 2

ans = -7

Octave also knows about parenthesis to overcome the natural precedence of operators. So let's rephrase the last example:

```
octave:6> (2 -3) * (4 +6) / 2
```

ans = -5

Octave also knows about the basic functions. The trigonometric family with sine, cosine and tangent, as well as the exponential ones like exp and logarithm. All of those simple functions are abbreviated, so you have sin, cos, tan, exp and log.

Let's see, if exp of one is equal to e (Euler's number):

```
octave:7> exp (1) - e
```

ans = 0

octave:8> exp(2) - e^2

ans = 8.88178419700125e-16

We get a very small number here, which is due to floating point errors. The results of e^2 and exp(2) have an endless series of digits after the decimal point and so have to be rounded. I don't know why we get different rounding errors, but 8.88 * 10^(-16) (or 8.88e-16) is very close to zero. These things can happen quite a lot, when working with irrational numbers and numeric approaches to problems in general. (Note: Octave solves problems numerically, the other precise way is to solve them symbolically.)

```
octave:9> log(e)
```

ans = 1

octave:10> sin (0.5 * pi)

ans = 1

Another useful function is square root, abbreviated to sqrt:

```
octave:11> sqrt (4)
```

ans = 2

octave:12> sqrt (2)

ans = 1.41421356237310

Now in real life you won't just solve such simple problems, but bigger ones, where you need to store temporary results and continue working with them. That's no problem in Octave, that's what variables are for. It's very simple and intuitive to work with them. Consider this example:

```
octave:13> A = 2 * log (e) + 7
```

A = 9

octave:14> A + 17 - 2 * A

ans = 8

That way you can assign multiple variables and work with them just like any other number.

NOTE: you must always use the multiplication operator *, so you can't just write: 2A ! If you have worked with other math programs before, you will know that.

Vectors and matrices in Octave are written the same way. A vector is just a matrix with one row. Vectors and matrices are used to represent functions and equations, so you should know about them to follow the next sections.

Let's start by writing a vector:

```
octave:15> V = [6, 8, 2]
```

V =

6 8 2

Now we have a vector with three elements, namely 6, 8 and 2. Elements are separated by commas, you don't have to use spaces, but it makes things easier to read.

Rows in matrices are separated by semicolons, so a two-by-two matrix would be written like this:

`octave:16> M = [6, 1; 10, 1];`

The first row will contain 6 and 1, the second row 10 and 1.

Now that, we have seen, that it's easy to write them, let's do something useful with them.

Let's solve a simple linear equation. The equation is:

```
6 x + 1 y = 112
```

10 x + 1 y = 184

We can use the left division operator - backslash - to solve this. So we have to write a 2x2 matrix containing the x and y part and a 1x2 matrix containing the results (result vector).

We already have the 2x2 matrix M, which represents the x and y part of the equation.

```
octave:17> R = [112; 184];
```

octave:18> V = M \ R

V =

18.0000

4.0000

So Octave displays the result. Still the result stays stored in the variable V, which is a 1x2 matrix.

NOTE: the V = isn't compulsory in the line V = M \ R.

There are two ways of representing a polynomial in Octave. One specific to just polynomials another more general. We will start with the general way of representing it as a function.

To enter a function in Octave is straight forward. Let's say we want to enter the function:

`f(x) = 12x^4 - 15x^2 - 22x +5`

First we must tell Octave, that we are writing a function:

`octave:19> function f(x)`

Now Octave responds with a prompt showing only a greater than ">" sign. Now we can enter the body of the function:

`> 12 * x^4 - 15 * x^2 -22 * x +5`

Octave still shows the prompt ">". It is still waiting for us to complete our function. So we tell it, that the function is complete:

`> endfunction`

Now we can evaluate the function for specific x's:

```
octave:20> f(1)
```

ans = -20

octave:21> f(2.5)

ans = 325

Octave has no concept of specific types, at least not the way we entered function f, so we can also do this:

```
octave:22> f([6, 1; 10, 1])
```

ans =

30455 4666

46615 7150

That way you can write all sorts of functions. You can create mathematical function of all kinds as well as functions in the sense used in programming languages. But for this workshop we will stop here.

The other way of representing a polynomial is as a vector of coefficients. So for the the polynomial function:

`f(x) 12x^4 - 15x^2 -22x +5`

We will have the vector:

`P = [12, 0, -15, -22, 5]`

Note that we have to include 0 coefficients, otherwise Octave won't know, where to skip a power of x. In Octave you will write it as:

`octave:23> P = [12, 0, -15, -22, 5]`

You can also evaluate this polynomial for specific x's, with the function polyval. The polyval function takes as its parameters the vector representing the function and the value of x, so to evaluate our polynomial P at x = 9, we type:

```
octave:24> polyval(P,9)
```

ans = 77324

Now, that we know, how to simply evaluate polynomial functions, we might wish to derive them for curve sketching. This also requires the vector form of representation, since we continue to work with the poly-functions from Octave. Consider the function from the earlier example:

`f(x) = 12x^4 - 15x^2 -22x +5`

Now we can find the coefficients for the first derivation by using polyder or polyderiv; they are synonyms:

```
octave:25> PDER = polyder(P)
```

ans =

48 0 -30 -22

Now you could write a function for the derived polynomial, which would look like this:

```
octave:26> function fder(x)
```

> 48 *x^3 -30 * x -22

> endfunction

You could evaluate it at x = 5 by typing:

```
octave:27> fder(5)
```

ans = 5828

Fortunately we stored the result of polyder in the vector PDER though, which represents a polynomial already, so we can just evaluate it with:

```
octave:28> polyval(PDER,5)
```

ans = 5828

But what you really want from that function is to find its roots. Octave does provide for that. It again uses the coefficient vector notation. Now let's find the roots of PDER:

```
octave:29> roots(PDER)
```

ans =

1.03364 + 0.00000i

-0.51682 + 0.41990i

-0.51682 - 0.41990i

So there's only one real solution, the other all have imaginary parts. Beware, that these are numerical approximations, so you end up having inexact values. But still let's try to evaluate our derived function fder with the third root, just to verify, that Octave hasn't given us complete gibberish:

```
octave:30> fder(1.03364)
```

ans = -2.5516e-04

So with the functions polyval, polyder and roots you can do your basic curve sketching with good numerical approximations.

Now that you've seen, how to do derivation, the next step would be to do integration, which is just as easy.

Let's take the polynomial P again:

`f(x) = 12x^4 - 15x^2 - 22x +5`

To find the coefficients for its integral we use polyint and just to be on the save side, we again store the result in a vector:

```
octave:31> PINT = polyint(P)
```

PINT =

2.40000 0.00000 -5.00000 -11.00000 5.00000

So now it will be easy to calculate an area in the boundaries of say 3 and 6. What do you have to do for that?

- Evaluate the the new function at 6 and 3
- and then subtract the results.

```
octave:32> polyval(PINT, 6) - polyval(PINT, 3)
```

ans = 1.6852e+04

Of course you might end up with a negative value, which tells you, that the lower and upper boundary should be swapped. To avoid having cancellation of areas above and below the x-axis, you can make sure by computing the roots of the original function again.

```
octave:33> roots(P)
```

ans =

1.51036 + 0.00000i

-0.85553 + 0.80166i

-0.85553 - 0.80166i

0.20070 + 0.00000i

Especially when you do big calculations, which you would like to share, you might be looking for a way to export or save a complete Octave session. Now we have good news and bad news. The bad news first: you can't directly save a complete session. But there is a workaround. We will come to that in a minute. What you can do however, is save all the variables of your current Octave session. This indeed is very simple:

```
octave:34> My_matrix = [ 1, 2; 3, 4 ];
```

My_matrix =

1 2

3 4

octave:35> My_number = 42.42

My_number = 42.420

octave:36> save("my_variables.mat")

Next time you start Octave you can use the command load like this:

`octave:37> load("my_variables.mat")`

To make sure the variables are there you can type:

`octave:38> My_number`

You can save in a lot of formats, including a few versions of Matlab. Here's an example of how it would look, if we saved our variables in a Matlab version 6 file:

`octave:39> save("-v6","my_Matlab.mat")`

Save also has a command form. The form we have been using is called the "functional form", since it looks like a call to a mathematical or programming style function. The "command form"; omits the parenthesis and doesn't require double quoting text arguments like filenames and options. So to save our variables to a Matlab version 6 file, we can also write:

`octave:40> save -v6 my_other_Matlab.mat`

Load also has a "command form", which is just as easy:

`octave:41> load my_other_Matlab.mat`

Now I promised, that there is a workaround to save a complete session. Octave has a command history. this history is saved in a file. Under Linux - and probably Mac OS - this is stored in the user's home directory as ".octave_hist". So you can remove the current history file, start Octave and write all the necessary commands, that you wish to share. Then you can rename - move - the file ".octave_hist" to a more explanatory name, like "math_project_for_analysis.oct". Then you can use any text editor to open the file and remove the last Octave command, which will be quit or exit. Now anyone can "import" your session by typing:

`octave:42>source math_project_for_analysis.oct`

All commands from the file will be executed.

A more reasonable way would be to directly write a script file. Just open a text editor and write Octave commands and functions, one per line. Save the file as ASCII or dos text. Octave doesn't require a specific filename extension. Pick any extensions you like, as long as it seems clear and stick with it! You can load these files in the same way as described above.

Working with Octave has the added bonus of being compatible with Matlab, a math application widely used at universities and other institutions. If your Matlab material isn't completely compatible with Octave, you can always send a mail to the Octave team and describe the differing behaviour. They seek to resolve such issues fully. Beyond the Matlab compatibility, Octave has some more extensions, so importing Octave scripts into Matlab might not always work that smoothly. Check the Octave documentation, if unsure about compatibility issues.

Octave can also be further extended by the user base. You can already install quite a few extra Octave packages on Linux and probably download them for Windows and Mac OS. You can extend Octave yourself by writing your own functions. The documentation contains some guidance and the website offers more help here. they also have a mailing-list.

You can also plot figures to the screen. Octave gives you the choice of using gnuplot or openGL - using the FLTK toolkit. So there are ways to visually interact with sighted people, purely controlled by the command line. The plotting output is controlled by the graphics_toolkit function, described in chapter 15 of the Octave online documentation.

You can also save and print plots in Octave. Octave allows saving to a variety of formats. Formats include the printer friendly ps, pdf and tex, as well as more screen oriented png, jpeg and gif. The format can be detected from the device option to the print command or from the filename extension.

As mentioned before, Octave can handle more than the few bits of math shown here. Differential equations, statistics, logic, optimisation, image and audio processing, handling sets, etc. All of which is described in the online documentation.

Perhaps we should end this workshop with one last - more or less practical - example. As said, Octave can be extended by other packages. Now it could be interesting to see, which packages are already installed. To do that type:

`Octave:43> pkg list`

This will give you a list of all currently installed packages on your system. It will also provide some details about each package. If you download a new package and wish to install it, you can do that from inside Octave, with the command "pkg install". So if the package is called image-0.1.0.tar.gz, the command would be:

`octave:44> pkg install image-0.1.0.tar.gz`

Now if you find, that the image package doesn't perform to your expectations, you can easily remove it. First you need to find it's name in Octave:

`octave:45> pkg list`

Assuming it is just called image, then you could remove it by typing:

`octave:46> pkg uninstall image`

But before that you might wish to use your newly installed package. Normally it should be loaded at the moment you install it. If it is not, you can use the "pkg load" command like this:

`octave:47> pkg load image`

And if it gets in your way:

`octave:48> pkg unload image`

I hope, that you have enjoyed this workshop and that you learnt something useful here, that you can integrate into your work at school, university or your job. If you think, that Octave could ease your math work, then I really recommend looking at the Octave online documentation. It is really good!

Thanks go to the Octave team for a wonderful application and extensive docs! I of course also wish to thank the organisers of the Summer University 2012 and our gracious hosts here in Linz: vielen Dank!

This workshop contains quotes from the Octave man page and the Octave online documentation.

This section contains a small list of Octave keywords, functions and commands to get you started. For more info see the Octave Documentation as described in section Getting help.

Short explanation of option syntax:

- N_something: means any number integer (no decimal point), floating point (with decimal point) and complex (if applicable)
- V_something: means any vector or matrix (if applicable)
- S_something: means any string (that is text)

- a + b or +b - plus operator
- a - b or - b - minus operator
- a / b - division operator
- a * b - multiplication operator
- a^b - to the power of operator
- M \ R - left division operator for matrices
- [ a1, b1, ... ] - braces to write a vector
- [ a1, b1, ...; a2, b2, ...;... ] - braces to write a matrix
- (a, b) - parenthesis used for function parameters and for precedence in mathematical expressions
- balance(V_matrix) - balance the matrix V_matrix. Eigenvalue calculations are usually improved, if the matrix is first balanced
- cond(V_matrix) - compute the p-norm condition of matrix V_matrix
- cos(N_angle) - cosine of N_angle. where N_angle is usually between 0 and 2 * pi
- det(V_matrix) - compute the determinant of the matrix V_matrix
- e - variable constant: Euler's number
- eig(V_matrix) - compute the eigenvalue, eigenvalue vector of the matrix V_matrix
- exp(N_value) - compute the exp function of N_value, meaning e^N_value.
- hadamard(N_n) - create a hadamard matrix with the size of N_n-by-N-n. N_n must be 2^k * p, where p can be 1, 12, 20 or 28. The matrix is normalised.
- hilb(N_n) - create a hilbert matrix of order N_n.
- I - variable constant: the pure imaginary unit i, defined as sqrt(-1)
- Inf - variable constant: infinity
- load S_file - this loads the file named S_file, which contains Octave variables.
- log(N_value) - compute the natural logarithm of N_value.
- magic(N_n) - create a matrix containing a magic square of the size N_n-by-N_n.
- NaN - variable constant: Not a Number, this is defined by the IEEE floating point standard and is returned, when an operation doesn't return a well defined number
- pi - variable constant: pi
- polyderiv(V_polynomial) - return the vector containing the coefficients of the derived function of V_polynomial
- polyint(V_polynomial) - return the coefficient vector of the integral function of V_polynomial
- polyval(V_polynomial,N_value) - computer the polynomial function, whose coefficients are stored in V_polynomial, at x = N_value
- roots(V_polynomial) - find all roots of the polynomial, whose coefficient vector is stored in V_polynomial
- rot90(V_matrix) - rotate the matrix V_matrix 90 degrees counterclockwise.
- rot90(V_matrix,N_times) - rotate V_matrix N_times times 90 degrees counterclockwise
- round(N_value) - round N_value to the nearest integer.
- save S_file - save all variables of the current session to the file named S_file.
- sin(N_angle) - sine of N_angle, where N_angle is usually between 0 and 2 * pi
- sqrt(N_value) - compute the square root of N_value
- tan(N_angle) - tangent of N_angle, where N_angle is usually between 0 and 2 * pi

Octave Workshop - copyright © 2011-2012 Julien Claassen.

[End of document]