Home Programming GNU Octave Beginner's Guide

GNU Octave Beginner's Guide

By Jesper Schmidt Hansen
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introducing GNU Octave
About this book
Today, scientific computing and data analysis play an integral part in most scientific disciplines ranging from mathematics and biology to imaging processing and finance. With GNU Octave you have a highly flexible tool that can solve a vast number of such different problems as complex statistical analysis and dynamical system studies.The GNU Octave Beginner's Guide gives you an introduction that enables you to solve and analyze complicated numerical problems. The book is based on numerous concrete examples and at the end of each chapter you will find exercises to test your knowledge. It's easy to learn GNU Octave, with the GNU Octave Beginner's Guide to hand.Using real-world examples the GNU Octave Beginner's Guide will take you through the most important aspects of GNU Octave. This practical guide takes you from the basics where you are introduced to the interpreter to a more advanced level where you will learn how to build your own specialized and highly optimized GNU Octave toolbox package. The book starts by introducing you to work variables like vectors and matrices, demonstrating how to perform simple arithmetic operations on these objects before explaining how to use some of the simple functionality that comes with GNU Octave, including plotting. It then goes on to show you how to write new functionality into GNU Octave and how to make a toolbox package to solve your specific problem. Finally, it demonstrates how to optimize your code and link GNU Octave with C and C++ code enabling you to solve even the most computationally demanding tasks. After reading GNU Octave Beginner's Guide you will be able to use and tailor GNU Octave to solve most numerical problems and perform complicated data analysis with ease.
Publication date:
June 2011
Publisher
Packt
Pages
280
ISBN
9781849513326

 

Chapter 1. Introducing GNU Octave

This chapter will introduce you to GNU Octave. We shall briefly discuss what GNU Octave is, its strengths and its weaknesses. You will also see GNU Octave in action; however, before this it must, of course, be installed on your computer, and we will quickly go through the installation procedure.

More specifically, in this chapter you will:

  • Get a quick introduction to GNU Octave.

  • Learn how to install GNU Octave on Windows and GNU/Linux.

  • Give GNU Octave a few commands to see it in action.

  • Customize GNU Octave.

  • Install additional packages.

  • Learn a few tricks of the trade.

GNU Octave exists for Mac/OS X, Solaris, and OS/2, but we will limit ourselves to go through the installation procedures for Windows and GNU/Linux. I strongly recommend that you install the most recent version of GNU Octave (which will be version 3.2.4 or higher). Many features described in this book are not supported in the version 2-series, especially, as the plotting facilities improved significantly in recent versions.

So what is GNU Octave?

In brief, GNU Octave is a multi-functional tool for sophisticated numerical analysis. GNU Octave provides you with:

  1. 1. A large set of build-in functionalities to solve many different problems.

  2. 2. A complete programming language that enables you to extend GNU Octave.

  3. 3. Plotting facilities.

This book will cover these features.

GNU Octave uses an interpreter to compile and execute a sequence of instructions given by the user at run-time. This is also how, for example, PHP and Python work. This is in contrast to pre-compiled programming languages such as C where the program is first compiled and then executed manually. Just like Python, you can give GNU Octave instructions in a prompt-like environment. We shall see many examples of this later. The following image shows a screenshot of GNU Octave in action—do not worry about what the plots are, for the time being.

GNU Octave is named after the chemist Octave Levenspiel and has nothing to do with music and harmonic waves. The project was started by James B. Rawlings and John G. Ekerdt, but it has mainly been developed by John W. Eaton, who has put a lot of effort into the project. GNU Octave is an official GNU project (hence, the GNU prefix), and the source code is released under the GNU General Public License (GPL).

In simple terms, this means that you are allowed to use the software for any purpose, copy, and distribute it, and make any changes you want to it. You may then release this new software under GPL. If you use GNU Octave's own programming language to extend the functionality, you are free to choose another license. I recommend you to have a look at the license agreement that comes with GNU Octave at http://www.gnu.org/software/octave/license.html.

In the remainder of the book, GNU Octave will simply be referred to as Octave for convenience. However, if you wish to sound like an Octave guru, use the "GNU" prefix!

Applications

As mentioned previously, Octave can be used to solve many different scientific problems. For example, a Copenhagen-based commercial software and consulting company specializes in optimization problems, especially for packing containers on large cargo ships. This can be formulated in terms of linear programming which involves solving large linear equation systems and to this end, the company uses Octave. Pittsburgh supercomputing center also used Octave to study social security number vulnerability. Here Octave ran on a massive parallel computer named Pople with 768 cores and 1.5 TB memory and enabled researches to carry out sophisticated analysis of different strategies before trying out new ones.

In the research community, Octave is used for data analysis, image processing, econometrics, advanced statistical analysis, and much more. We shall see quite a few examples of this throughout the book.

Limitations of Octave

Octave is mainly designed to perform numerical computations and is not meant to be a general purpose programming language such as C or C++. As it is always the case, you should choose your programming language depending on the problem you wish to solve. Nevertheless, Octave has a lot of functionality that can help you with, for example, reading from and writing to files, and you can even use a package named sockets for accessing a network directly.

The fact that Octave uses an interpreter means that Octave first has to convert the instructions into machine readable code before executing it. This has its advantages as well as drawbacks. The main advantage is that the instructions are easy to implement and change, without having to go through the edit, compile, and run phase and gives the programmer or user a very high degree of control. The major drawback is that the program executes relatively slowly compared to pre-compiled programs written in languages such as C or Fortran. Octave is therefore perhaps not the first choice if you want to do extremely large scale parallelized computations, such as state-of-art weather forecasting.

However, as you will experience later in the book, Octave will enable you solve very advanced and computationally demanding problems with only a few instructions or commands and with satisfactory speed. The last chapter of this book teaches you some optimization techniques and how you can use C++ together with Octave to speed things up considerably in some situations.

Octave is not designed to do analytical (or symbolic) mathematics. For example, it is not the best choice if you wish to find the derivative of a function, say f (x) = x2. Here software packages such as Maxima and Sage can be very helpful. It should be mentioned that there exists a package (a package is also referred to as a toolbox) for Octave which can do some basic analytical mathematics.

Octave and MATLAB

It is in place to mention MATLAB. Often Octave is referred to as a MATLAB-clone (MATLAB is a product from MathWorksTM). In my opinion, this is wrong! Rather, Octave seeks to be compatible with MATLAB. However, be aware, in some cases you cannot simply execute your Octave programs with MATLAB and vice-versa. Throughout the book, it will be pointed out where compatibility problems can occur, but we shall stick with Octave and make no special effort to be compatible with MATLAB.

The Octave community

The newest version of Octave can be found on the web page http://www.octave.org. Here you will also find the official manual, a Wiki page with tricks and tips, latest news, a bit of history, and other exciting stuff. From this web page, you can join Octave's mailing lists (the help-list is especially relevant), which only require a valid email address. The user community is very active and helpful, and even the developers will answer "simple" user questions. You can also learn quite a lot from browsing through the older thread archives.

There also exists an Usenet discussion group http://groups.google.com/group/comp.soft-sys.octave/topics?lnk. Unfortunately, this group seems quite inactive, so it could take a while for help to arrive.

There exist a very large number of additional packages that do not come with the standard Octave distribution. Many of these can be downloaded from the Octave-Forge http://octave.sourceforge.net. Here you will find specially designed packages for imaging processing, econometrics, information theory, analytical mathematics, and so on. After reading this book and solving the problems at the end of each chapter, you will be able to write your own Octave package. You can then share your work with others, and the entire Octave community can benefit from your efforts. Someone might even extend and improve what you started!

 

So what is GNU Octave?


In brief, GNU Octave is a multi-functional tool for sophisticated numerical analysis. GNU Octave provides you with:

  1. 1. A large set of build-in functionalities to solve many different problems.

  2. 2. A complete programming language that enables you to extend GNU Octave.

  3. 3. Plotting facilities.

This book will cover these features.

GNU Octave uses an interpreter to compile and execute a sequence of instructions given by the user at run-time. This is also how, for example, PHP and Python work. This is in contrast to pre-compiled programming languages such as C where the program is first compiled and then executed manually. Just like Python, you can give GNU Octave instructions in a prompt-like environment. We shall see many examples of this later. The following image shows a screenshot of GNU Octave in action—do not worry about what the plots are, for the time being.

GNU Octave is named after the chemist Octave Levenspiel and has nothing to do with music and harmonic waves. The project was started by James B. Rawlings and John G. Ekerdt, but it has mainly been developed by John W. Eaton, who has put a lot of effort into the project. GNU Octave is an official GNU project (hence, the GNU prefix), and the source code is released under the GNU General Public License (GPL).

In simple terms, this means that you are allowed to use the software for any purpose, copy, and distribute it, and make any changes you want to it. You may then release this new software under GPL. If you use GNU Octave's own programming language to extend the functionality, you are free to choose another license. I recommend you to have a look at the license agreement that comes with GNU Octave at http://www.gnu.org/software/octave/license.html.

In the remainder of the book, GNU Octave will simply be referred to as Octave for convenience. However, if you wish to sound like an Octave guru, use the "GNU" prefix!

Applications

As mentioned previously, Octave can be used to solve many different scientific problems. For example, a Copenhagen-based commercial software and consulting company specializes in optimization problems, especially for packing containers on large cargo ships. This can be formulated in terms of linear programming which involves solving large linear equation systems and to this end, the company uses Octave. Pittsburgh supercomputing center also used Octave to study social security number vulnerability. Here Octave ran on a massive parallel computer named Pople with 768 cores and 1.5 TB memory and enabled researches to carry out sophisticated analysis of different strategies before trying out new ones.

In the research community, Octave is used for data analysis, image processing, econometrics, advanced statistical analysis, and much more. We shall see quite a few examples of this throughout the book.

Limitations of Octave

Octave is mainly designed to perform numerical computations and is not meant to be a general purpose programming language such as C or C++. As it is always the case, you should choose your programming language depending on the problem you wish to solve. Nevertheless, Octave has a lot of functionality that can help you with, for example, reading from and writing to files, and you can even use a package named sockets for accessing a network directly.

The fact that Octave uses an interpreter means that Octave first has to convert the instructions into machine readable code before executing it. This has its advantages as well as drawbacks. The main advantage is that the instructions are easy to implement and change, without having to go through the edit, compile, and run phase and gives the programmer or user a very high degree of control. The major drawback is that the program executes relatively slowly compared to pre-compiled programs written in languages such as C or Fortran. Octave is therefore perhaps not the first choice if you want to do extremely large scale parallelized computations, such as state-of-art weather forecasting.

However, as you will experience later in the book, Octave will enable you solve very advanced and computationally demanding problems with only a few instructions or commands and with satisfactory speed. The last chapter of this book teaches you some optimization techniques and how you can use C++ together with Octave to speed things up considerably in some situations.

Octave is not designed to do analytical (or symbolic) mathematics. For example, it is not the best choice if you wish to find the derivative of a function, say f (x) = x2. Here software packages such as Maxima and Sage can be very helpful. It should be mentioned that there exists a package (a package is also referred to as a toolbox) for Octave which can do some basic analytical mathematics.

Octave and MATLAB

It is in place to mention MATLAB. Often Octave is referred to as a MATLAB-clone (MATLAB is a product from MathWorksTM). In my opinion, this is wrong! Rather, Octave seeks to be compatible with MATLAB. However, be aware, in some cases you cannot simply execute your Octave programs with MATLAB and vice-versa. Throughout the book, it will be pointed out where compatibility problems can occur, but we shall stick with Octave and make no special effort to be compatible with MATLAB.

The Octave community

The newest version of Octave can be found on the web page http://www.octave.org. Here you will also find the official manual, a Wiki page with tricks and tips, latest news, a bit of history, and other exciting stuff. From this web page, you can join Octave's mailing lists (the help-list is especially relevant), which only require a valid email address. The user community is very active and helpful, and even the developers will answer "simple" user questions. You can also learn quite a lot from browsing through the older thread archives.

There also exists an Usenet discussion group http://groups.google.com/group/comp.soft-sys.octave/topics?lnk. Unfortunately, this group seems quite inactive, so it could take a while for help to arrive.

There exist a very large number of additional packages that do not come with the standard Octave distribution. Many of these can be downloaded from the Octave-Forge http://octave.sourceforge.net. Here you will find specially designed packages for imaging processing, econometrics, information theory, analytical mathematics, and so on. After reading this book and solving the problems at the end of each chapter, you will be able to write your own Octave package. You can then share your work with others, and the entire Octave community can benefit from your efforts. Someone might even extend and improve what you started!

 

Installing Octave


Octave is primarily designed to run under GNU/Linux. However, you can also run Octave under Windows with only a few glitches here and there. The installation procedure, runs very smoothly under Windows. Let us start with this.

Windows

Installing Octave on Windows is straightforward. The steps are as follows:

  1. 1. Go to the Octave-Forge web site. Here there is a hyper link to a Windows installer. Download this installer onto your desktop or any other destination you may prefer.

  2. 2. Double-click on the installer icon.

  3. 3. You will see a greeting window. Click on the Next button.

  4. 4. The next window shows you the license agreement, which I recommend that you read. Click the Next button.

  5. 5. Now, you will have the opportunity to choose where Octave will be installed. The default path is usually fine. When you are happy with the installation path, click on Next.

  6. 6. The following window asks you to choose between different versions of the FFTW3 and ATLAS numerical libraries that Octave uses for Fourier transforms and linear algebra computations. These different versions are specially designed for different CPU architectures. You can also choose any additional packages you want to install, as shown in the following screenshot. Let us not worry about the details of the FFTW3 and ATLAS libraries at the moment, and just choose the generic versions for now.

  7. 7. Choose to install all additional packages by ticking the Octave-Forge box. Click on Next and Octave will get installed.

  8. 8. After the installation, you can change the menu folder if you wish. If you want, you can also check the README file, and if not, simply uncheck the box to the left of where you are asked whether you want to see the README file. Click Next, and you are done!

Note

This installation guide has been tested on 32-bit Windows 2000, Windows XP, and Windows 7.

Notice that Octave's interactive environment (the Octave prompt) may be launched when the installer exits. To close this, simply type:

octave:1> exit

or press the Ctrl key and the D key at the same time. We shall write this combination as Ctrl + D. By the way, Ctrl + D is a UNIX end-of-file indicator and is often used as a shortcut for quitting programs in UNIX-type systems like GNU/Linux.

Alternatively, you can run Octave under Windows through Cygwin, which is similar to the GNU/Linux environment in Windows. I will not go through the installation of Cygwin here, but you may simply refer to the Cygwin web page http://www.cygwin.com.

Note

If you install Octave version 3.2.4 under Windows, I strongly recommend that you leave out the oct2mat package. This package may prevent the plotting window to update properly. For instance, when you plot a graph, it will not appear in the plotting window. This is not an issue under GNU/Linux.

GNU/Linux

On many GNU/Linux distributions, Octave is a part of the standard software. Therefore, before installing Octave, check if it already exists on your computer. To do so, open a terminal, and type the following in the terminal shell:

$ octave

If Octave is installed (properly), you should now see Octave's command prompt. Now just exit by typing the following:

octave:1> exit

Alternatively, you may use CTRL + D, that is, press the control key and the D key at the same time.

If Octave is not installed, you can often use the distribution's package management system. For example, for Ubuntu, you can use the Synaptic Package Manager, which is a graphical tool to install and remove software on the computer. Please refer the following screenshot. In case of Fedora and CentOS, you can use YUM.

Note

Make sure that your package manager also installs a plotting program with Octave, for example, gnuplot.

Building Octave from the source under GNU/Linux

If you wish, you can also build Octave directly from the source code. However, I only recommend this if Octave is not available through the system's package manager. In order to build Octave from source, you will need (at least) the following:

  • The GNU make utility

  • Fortran and C/C++ compilers (GNU Compiler Collection (known as GCC) version 4.1 or later suffice)

  • gnuplot (to be on the safe side)

Fortunately, these software packages usually come with most GNU/Linux distributions. If not, you should be able use the package manager to install them.

 

Time for action - building Octave from source


Perform the following actions step-by-step:

  1. 1. Download the latest stable release of Octave from http://www.gnu.org/software/octave/download.htm and save it to any directory. The file will be a compressed and archived file with extension .tar.gz.

  2. 2. Open a terminal and enter the directory where the source was downloaded. To unpack the file, type the following:

    $ tar zxf octave-version.tar.gz
    
  3. 3. Here version will be the version number. This command will create a directory named octave-version.

  4. 4. To enter that directory type the following:

    $ cd octave-version
    
  5. 5. We can now configure the building and compiling processes by typing the following:

$ ./configure
  1. 6. If the configuration process is successful, then we can compile the Octave source with the following command(this will take a while):

$ make
  1. 7. Before doing the actual installation, you should test whether the build was done properly. To do so, type the following:

$ make check
  1. 8. Some of the tests may fail. However, this does not mean that the build was unsuccessful. The test is not mandatory.

  2. 9. To install Octave on the computer, you need to have root privileges. For example, you can use the following:

    $ sudo make install
    
  3. 10. Now type in the root password when prompted. That is it!

What just happened?

As you can see, we just performed the standard UNIX installation procedure: configure, make, make install. If you do not have root privileges, you cannot install Octave on the computer. However, you can still launch Octave from the bin/ sub-directory in the installation directory.

Again, the preceding installation will only install Octave and not the plotting program. You will need to have this installed separately for Octave to work properly.

Note

I recommend that you have Emacs installed under GNU/Linux, because Octave uses this as the default editor. You will learn how to change the default editor later.

 

Checking your installation with peaks


It is time to take Octave for a spin! There are different ways to start Octave's interpreter. One way is to execute an Octave script, and another way is to enter Octave's interactive environment, which is what we will do here.

 

Time for action - testing with peaks


  1. 1. You can enter the interactive environment by typing octave in your shell under GNU/Linux, or by double-clicking the Octave icon in Windows. You should now see the Octave prompt:

octave:1>
  1. 2. You have already learned how to exit the interactive environment. Simply give Octave the command exit or press Ctrl + D, but we do not want to exit just yet!

  2. 3. At the prompt, type as follows:

octave:1> surf(peaks)
  1. 4. You should now see a three-dimensional surface plot as depicted on the left-hand side figure shown next. If not, your installation has not been successful. Now, put your mouse pointer over the figure window, hold the left mouse button down, and move the pointer. If the plotting program supports it, the figure should now rotate in the direction you move the pointer. If you click on the figure window using mouse button three (or the scroll wheel) you can zoom by moving the pointer side to side or up and down.

  2. 5. Let us try a contour plot. Type as follows:

octave:2> contourf(peaks)
  1. 6. Does it look like the following figure on the right? If not, it can be because you are using Octave version 3.2.4 and have the package oct2mat loaded. Try typing

octave:3> pkg unload oct2mat
  1. 7. Now retype the previous command.

  2. 8. Click somewhere on the window of the right-hand side figure with button three. A cross and two numbers appear in the window if you are using gnuplot with Octave. The cross is just the point where you clicked. The two numbers show the x axis and y axis values.

Note

Octave can use different plotting program, for example, gnuplot or its own native plotting program. Therefore, your figures may look a bit different, depending on that program.

What just happened?

The figure to the left shows a graph of a mathematical function, which is a scalar function of two variables y and x given by:

(1.1)

The function value (range) is evaluated in Octave by the command peaks, which is the nick name for the function f. The graph is then plotted using the Octave function surf. As a default, Octave calculates the range of f using 50 x and y values in the interval [ 3; 3]. As you might have guessed already, the contourf Octave function plots the contours of f. Later we will learn how to label the axis, add text to the figures, and much more.

Did you notice the phrase "Octave function" previously? An Octave function is not necessarily a mathematical function as Equation (1.1), but can perform many different types of operations and have many different functionalities. Do not worry about this for now. We will discuss Octave functions later in the book.

Notice that the interpreter keeps track of the number of commands that have been entered and shows this at the prompt.

 

Customizing Octave


When the Octave interpreter starts, it reads several configuration files. These files can be changed in order to add system paths, the appearance of the Octave command prompt, how the editor behaves, and much more. The changes can be global and affect all users of Octave that run on a particular computer. They can be targeted to work with a specific version of Octave, a specific project, or a user. This is especially useful on multi-user platforms, such as GNU/Linux.

The configuration files are named either octaverc or .octaverc, depending on where they are located and how the configurations affect Octave. They basically consist of a sequence of Octave commands, so you can also give the same commands to the interpreter from the Octave prompt. This can be a good way to test new configurations before implementing them in your octaverc or .octaverc files.

The names octaverc and .octaverc are, of course, not supported by MATLAB. However, most commands are. It is therefore just a matter of copying the content of the octave configuration files into MATLAB's startup.m file.

Under Windows, the user does not have a home directory equivalent to the home directory under GNU/Linux. I therefore recommend that you create a home directory for Octave. You can then command Octave to go to this directory and look for your configuration file here, whenever you start the interpreter.

If you are using GNU/Linux you can skip the following "Time for action" section.

 

Time for action - creating an Octave home directory under Windows


Let us assume that the Octave home directory is going to be C:\Documents and Settings\GNU Octave\. We can actually create this directory directly from Octave; so let us go ahead.

  1. 1. Start Octave and give it the following commands:

octave:1> cd C:
octave:2> cd "Documents and Settings"
octave:3> mkdir "GNU Octave"
ans = 1
  1. 2. The response ans = 1 after the last command means that the directory was successfully created. If Octave returns a zero value, then some error occurred, and Octave will also print an error message. Instead of creating the directory through Octave, you can use, for example, Windows Explorer.

  2. 3. We still need to tell the interpreter that this is now the Octave home directory. Let us do this from Octave as well:

octave:4> edit
  1. 4. You should now see an editor popping up. The default editor under Windows is Notepad++. Open the file c:\octave-home\share\octave\site\m\startup\octaverc, where octave-home is the path where Octave was installed, for example, Octave\3.2.4_gcc-4.4.0. Add the following lines at the end of the file.

    setenv('HOME', 'C:\Document and Settings\GNU Octave\');
    cd ~/
    
  2. Be sure that no typos sneaked in!

  3. 5. Save the file, exit the editor, and restart Octave. That is it.

Note

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

What just happened?

The first three Octave commands should be clear: we changed the directory to C:\Documents and Settings\ and created the directory GNU Octave. After this, we opened the global configuration file and added two commands. The next time Octave starts it will then execute these commands. The first instructed the interpreter to set the home directory to C:\Document and Settings\GNU Octave\, and the second made it enter that directory.

Creating your first .octaverc file

Having created the Octave home directory under Windows, we can customize Octave under GNU/Linux and Windows the same way.

 

Time for action - editing the .octaverc file


  1. 1. Start Octave if you have not already done so, and open the default editor:

    octave:1> edit
    
    
  2. 2. Copy the following lines into the file and save the file as .octaverc under the Octave home directory if you use Windows, or under the user home directory if you use GNU/Linux. (Without the line numbers, of course.) Alternatively, just use your favorite editor to create the file.

    PS1 (">> ");
    edit mode "async"
    
  3. Exit the editor and restart Octave. Did the appearance of the Octave prompt change? It should look like this

    >>
    

    Note

    Instead of restarting Octave every time you make changes to your setup files, you can type, for example, octave:1> source(".octaverc"). This will read the commands in the .octaverc file.

What just happened?

PS1(">> ") sets the primary prompt string in Octave to the string given. You can set it to anything you may like. To extend the preceding example given previously, PS1("\\#>> ") will keep the command counter before the>> string. You can test which prompt string is your favorite directly from the command prompt, that is, without editing .octaverc. Try, for example, to use \\d and Hello give a command, \\u. In this book, we will stick with the default prompt string, which is \\s:\\#>.

The command edit mode "async" will ensure that when the edit command is given, you can use the Octave prompt without having to close the editor first. This is not default in GNU/Linux.

Finally, note that under Windows, the behavior will be global because we instructed Octave to look for this particular .octaverc file every time Octave is started. Under GNU/Linux, the .octaverc is saved in the user's home directory and will therefore only affect that particular user.

More on .octaverc

The default editor can be set in .octaverc. This can be done by adding the following line into your .octaverc file

edit editor name of the editor

where name of the editor is the editor. You may prefer a notepad if you use Windows, or gedit in GNU/Linux. Again, before adding this change to your .octaverc file, you should test whether it works directly from the Octave prompt.

Later in the book, we will write script and function files. Octave will have to be instructed where to look for these files in order to read them. Octave uses a path hierarchy when searching for files, and it is important to learn how to instruct Octave to look for the files in certain directories. I recommend that you create a new directory in your home directory (Octave home directory in Windows) named octave. You can then place your Octave files in this directory and let the interpreter search for them here.

Let us first create the directory. It is easiest simply to enter Octave and type the following:

octave1:> cd ~/
octave2:> mkdir octave

It should be clear what these commands do. Now type this:

octave3:> edit .octaverc

Add the following line into the .octaverc file:

addpath("~/octave");

Save the file, exit the editor, and restart Octave, or use source(".octaverc"). At the Octave prompt, type the following:

octave1:> path

You should now see that the path ~/octave/ is added to the search path. Under Windows, this path will be added for all users. The path list can be long, so you may need to scroll down (using the arrow key) to see the whole list. When you reach the end of the list, you can hit the Q key to return to Octave's command prompt.

 

Installing additional packages


As mentioned earlier, there exists a large number of additional packages for Octave, many of which can be downloaded from the Octave-Forge web page. Octave has a superb way of installing, removing, and building these packages. Let us try to install the msh package, which is used to create meshes for partial differential solvers.

 

Time for action - installing additional packages


  1. 1. Before installing a new package, you should check which packages exist already and what their version numbers are. Start Octave, if you have not done so. Type the following:

octave:1> pkg list
  1. 2. You should now see a table with package names, version numbers, and installation directories. For example:

    Package Name | Version | Installation directory --------------------+-----------+------------------------------------ combinatorics | 1.0.6 | /octave/packages/combinatorics-1.0.6

  2. 3. If you have chosen to install all packages in your Windows installation, the list is long. Scroll down and see if the msh package is installed already, and if so, what the version number is. Again, you can press the Q key to return to the prompt.

  3. 4. Now go to the Octave-Forge web page, find the msh package, and click on Details (to the right of the package name). You will now see a window with the package description, as shown in the following figure. Is the package version number higher than the one already installed? (If not, sit back, relax, and read the following just for the fun of it.) The package description also shows that the msh package dependents on the spline package and Octave version higher than 3.0.0. Naturally, you need Octave. However, the spline package may not be installed on your system. Did you see the spline package when you typed pkg list previously? If not, we will need to install this before installing msh. Go back to the main package list and download the msh and the spline packages to your Octave home directory. (By the way, does the spline package have any dependencies?) The downloaded files will be archived and compressed and have extensions .tar.gz. To install the packages, make sure you are in your Octave home directory and type the following:

octave:2> pkg install splines-version-number.tar.gz
  • (If you need it.)

octave:3> pkg install msh-version-number.tar.gz
  1. 5. Make sure that you have downloaded the package files into the Octave home directory.

  2. 6. To check your new package list, type the following:

octave:4> pkg list
  • Package Name | Version | Installation directory ---------------------+------------+----------------------------- combinatorics | 1.0.6 | /octave/packages/combinatorics-1.0.6 msh | 1.0.1 | /home/jesper/octave/msh-1.0.1 splines * | 1.0.7 | /home/jesper/octave/splines-1.0.7

  1. 7. You can get a description of the msh package by typing the following:

octave5:> pkg describe msh
---
Package name:
msh
Short description:
Create and manage triangular and tetrahedral meshes for Finite
Element or Finite Volume PDE solvers. Use a mesh data structure
compatible with PDEtool. Rely on gmsh for unstructured mesh
generation.
Status:
Not loaded
  1. 8. From the status, you can see that the package has not been loaded, which means we cannot use the functionality that comes with the package. To load it, simply type the following:

octave:6> pkg load msh
  1. 9. You should check that it actually has been loaded using pkg describe msh. Naturally, you can also unload the msh package by using the following command:

octave:7> pkg unload msh

Note

If you are using a multi-user system, consult your system administrator before you install your own local packages.

What just happened?

The important points have already been explained in detail. Note that you need to install splines before msh because of the dependencies.

You may find it a bit strange that you must first load the package into Octave in order to use it. The package can load automatically if you install it with the auto option. For example, command 3 can be replaced with the following:

octave:3> pkg install auto msh-version-number.tar.gz

Some packages will automatically load even though you do not explicitly instruct it to do so when you install it. You can force packages not to load using noauto.

octave:3> pkg install noauto msh-version-number.tar.gz

Uninstalling a package

Unistalling a package is just as easy:

octave:8> pkg uninstall msh

Note that you will get an error message if you try to uninstall splines before msh because msh depends on splines.

 

Getting help


The pkg command is very flexible and can be called with a number of options. You can see all these options by typing the following:

octave:9> help pkg

The help documentation is rather long for pkg. You can scroll up and down in the text using the arrow keys or the F and B keys. You can quit the help anytime by pressing the Q key. The previous example illustrates the help text for pkg. Help is also available for other Octave commands. You may try, for example, help PS1.

 

The behaviour of the Octave command prompt


Often you will use the same commands in an Octave session. Sometimes, you may have forgotten a certain command's name or you only remember the first few letters of the command name. Octave can help you with this. For example, you can see your previous commands by using the up and down arrow keys (Try it out!). Octave even saves your commands from previous sessions.

For example, if you wish to change the appearance of your primary prompt string, then type the following:

octave:10> PS <up arrow key>

Now only the previous commands starting with PS show up. Instead of using the arrow key, try to hit the tabulator key twice:

octave:11> PS

(Now press TAB key twice)

PS1 PS2 PS4

This shows all commands (and functions) available having PS prefixed.

 

Summary


In this chapter, you have learned the following:

  • About Octave, it's strengths, and weaknesses.

  • How to install Octave on Windows and GNU/Linux.

  • To test your installation with peaks.

  • How to use and change the default editor.

  • To customized Octave. For example, we saw how to change the prompt appearance and how to add search paths.

  • To use the pkg command to install and remove additional packages.

  • About the help utility.

We are now ready to move on and learn the basics about Octave's data types and operators.

About the Author
  • Jesper Schmidt Hansen

    Jesper Schmidt Hansen holds a Ph.D. in soft-material science and is currently doing research in the field of nanofluidics and dynamics at Roskilde University, Denmark. He has been using GNU Octave on a daily basis for many years, both as a student and later as a researcher. The applications have varied from solving partial and ordinary differential equations, simple data plotting, and data generation for other applications, to dynamical system investigations and advanced data analysis.

    Browse publications by this author
Latest Reviews (1 reviews total)
For me at least, this title was way too basic. When I look for what I would consider commonly needed tasks, I can't find them. A bit disappointing, but I have generally just Googled my questions instead of using the book.
GNU Octave Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now