Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
GNU Octave Beginner's Guide
GNU Octave Beginner's Guide

GNU Octave Beginner's Guide: Become a proficient Octave user by learning this high-level scientific numerical tool from the ground up

Arrow left icon
Profile Icon Jesper Schmidt Hansen
Arrow right icon
R$272.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (19 Ratings)
Paperback Jun 2011 280 pages 1st Edition
eBook
R$80 R$218.99
Paperback
R$272.99
Subscription
Free Trial
Renews at R$50p/m
Arrow left icon
Profile Icon Jesper Schmidt Hansen
Arrow right icon
R$272.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2 (19 Ratings)
Paperback Jun 2011 280 pages 1st Edition
eBook
R$80 R$218.99
Paperback
R$272.99
Subscription
Free Trial
Renews at R$50p/m
eBook
R$80 R$218.99
Paperback
R$272.99
Subscription
Free Trial
Renews at R$50p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

GNU Octave Beginner's Guide

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.

Left arrow icon Right arrow icon

Key benefits

  • The easiest way to use GNU Octave's power and flexibility for data analysis
  • Work with GNU Octave's interpreter ‚Äì declare and control mathematical objects like vectors and matrices
  • Rationalize your scripts and control program flow
  • Extend GNU Octave and implement your own functionality
  • Get to know the vast built-in functionality that GNU Octave has to offer
  • Build your own GNU Octave toolbox package to solve complex problems
  • Learn Octave the simple way, with real-world examples and plenty of screenshots provided throughout the book

Description

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.

Who is this book for?

This book is intended for anyone interested in scientific computing and data analysis. The reader should have a good level of mathematics and a basic understanding of programming will be useful, although it is not a prerequisite.

What you will learn

  • Work with the Octave interpreter
  • Declare and control different variable types
  • Use arithmetic operations between variables
  • Use logical operations
  • Control the program flow
  • Write scripts
  • Implement new functions
  • Perform complex data analysis
  • Write your own toolbox package
  • Optimize your code
Estimated delivery fee Deliver to Brazil

Standard delivery 10 - 13 business days

R$63.95

Premium delivery 3 - 6 business days

R$203.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 21, 2011
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781849513326
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Brazil

Standard delivery 10 - 13 business days

R$63.95

Premium delivery 3 - 6 business days

R$203.95
(Includes tracking information)

Product Details

Publication date : Jun 21, 2011
Length: 280 pages
Edition : 1st
Language : English
ISBN-13 : 9781849513326
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
R$50 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
R$500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts
R$800 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 518.98
GNU Octave Beginner's Guide
R$272.99
gnuplot Cookbook
R$245.99
Total R$ 518.98 Stars icon

Table of Contents

8 Chapters
Introducing GNU Octave Chevron down icon Chevron up icon
Interacting with Octave: Variables and Operators Chevron down icon Chevron up icon
Working with Octave: Functions and Plotting Chevron down icon Chevron up icon
Rationalizing: Octave Scripts Chevron down icon Chevron up icon
Extensions: Write Your Own Octave Functions Chevron down icon Chevron up icon
Making Your Own Package: A Poisson Equation Solver Chevron down icon Chevron up icon
More Examples: Data Analysis Chevron down icon Chevron up icon
Need for Speed: Optimization and Dynamically Linked Functions Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(19 Ratings)
5 star 47.4%
4 star 26.3%
3 star 21.1%
2 star 5.3%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Mar 10, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good for the questions posed. Yet to go through completely.
Amazon Verified review Amazon
TB (aus) Nov 08, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was very surprised by this book having tinkered with Octave since '96 so I was inspired to write a review.Best of all it is written specifically for Octave and I have learnt new tricks that would be hard pick up from the official documentation, which is mainly a reference. The book has a text book style with simple examples to teach good scripting techniques and the latest graphics commands. It is quite general and doesn't focus on specialised (hard core Math, Stats, Engineering) functions that come with Octave, as that's what the official documentation is for.I highly recommended getting this relatively cheap book as it will save you hours of time cross-checking between the official 'GNU Octave' documentation, the numerous Howtos, Lecture Notes, summary sheets scattered on the Net, many of which are now outdated and M@lab books just to get things going.
Amazon Verified review Amazon
Mark A. Lytle Apr 04, 2012
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good guide for someone with previous programming experience (at least some) or undergraduates with a math background who want to learn to use computers as a powerful math tool.The structure is well thought out, and the explanations are generally clear. The examples are well chosen also. I find myself hoping that Mr. Hanson might come out with a sequel, as Octave is rich enough to be worth more than one book.Octave is the free, open source alternative to Matlab, and will run many of the same scripts. With this entry, Octave shows it has matured, and has some momentum. I have spent about 2 weeks with this book and have only covered perhaps half of it's topics, but it is far more accessible then most college textbooks. I do recommend it for your bookshelf.
Amazon Verified review Amazon
Lugo Nov 06, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Su contenido es basico pero muy explicito en todo, muy practico y con todo lo necesario para comenzar a utilizar octave.
Amazon Verified review Amazon
Mouli Jul 03, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Best out of possibly only few books on GNU Octave. Good organization of concepts
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela