Crystal Structures and Expansion Anomalies of MnO, MnS, FeO, Fe3O4 (Кристаллические структуры и увеличение Аномалии в MnO, MnS, FeO, Fe3O4), страница 3

GNU Octave. Beginner’s Guide

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. A large set of build-in functionalities to solve many different problems.

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

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.

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. 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.

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++. Nevertheless, Octave has a lot of.

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.

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 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. 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, which only require a valid email address. The user community is very active and helpful, and even the developers will answer "simple" user questions.

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. 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. Double-click on the installer icon.

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

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

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. 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. Choose to install all additional packages by ticking the Octave-Forge box. Click on Next and Octave will get installed.

8. After the installation you can also check the README file. Click Next, and you are done!

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. 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.

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.

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. In case of Fedora and CentOS, you can use YUM.

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. 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

Fortunately, these software packages usually come with most GNU/Linux distributions.

Time for action - building Octave from source

Perform the following actions step-by-step:

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. 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. Here version will be the version number. This command will create a directory named octave-version.

4. To enter that directory type the following:

cd octave-version

5. We can now configure the building and compiling processes by typing the following: ./configure

6. If the configuration process is successful, then we can compile the Octave source with the following command:

make

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

make check

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

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

sudo make install

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.

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.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>

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!

3.At the prompt, type as follows:

octave:1> surf(peaks)

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.

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

octave:2> contourf(peaks)

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

7. Now retype the previous command.

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.

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:

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 off. 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, but can perform many different types of operations. 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.

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.

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

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.

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

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 OctaveV); cd ~/

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

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. Start Octave if you have not already done so, and open the default editor:

octave:1> edit

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.)

PS1    (">> ");

edit mode "async"

Exit the editor and restart Octave. Did the appearance of the Octave prompt change? It should look like this »

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. 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.

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. 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

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

combinatorics | 1.0.6   | /octave/packages/combinatorics-1.0.6

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.

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. However, the spline package may not be installed on your system. 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

5.    Make sure that you have downloaded the package files into the Octave home directory.

6. To check your new package list, type the following: octave:4> pkg list

combinatorics  |  1.0.6    | /octave/packages/combinatorics-1.0.6

msh

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

octave5:> pkg describe msh

Package name: msh

Short description:

Status:

Not loaded

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

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

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.

Глава 1

Введение в GNU Octave

Эта глава познакомит вас с GNU Octave. Мы коротко обсудим, что такое Octave, ее сильные и слабые стороны. Вы также увидите Octave в действии, но прежде, вы должны, конечно, установить эту программу на ваш компьютер. Мы быстро пройдем всю процедуру установки.

В этой главе вы:

• Получите основные инструкции по GNU Octave.

• Научитесь устанавливать GNU Octave в Windows и GNU/Linux.

• Выполните в GNU Octave несколько команд, чтобы увидеть ее в работе.

• Настройте GNU Octave для своих нужд.

• Установите дополнительные пакеты расширений.

• Научитесь некоторым профессиональным трюкам.

GNU Octave существует и в версиях для Mac/OS X, Solaris, и OS/2, но мы ограни­чимся лишь процедурой установки версий для Windows и GNU/Linux. Рекомендуется устанавливать самую последнюю версию GNU Octave (в момент написания - версия 3.2.4). Многие особенности, описанные в этой книге, не поддерживаются в более ранних версиях, особенно такие как графические возможности были существенно улучшены в последних версиях.

  Итак, что же такое GNU Octave?

Если коротко, то GNU Octave - мультифункциональный инструмент для изощренного численного анализа. GNU Octave предоставляет вам массу возможностей:

1. Огромный набор встроенных функций для решения большого круга различных задач.

2. Программный язык, который позволит вам расширить GNU Octave.

3. Возможности для построения разнообразных графиков.

В этой книге вы познакомитесь со всеми этими возможностями.

GNU Octave использует интерпретатор для компиляции и выполнения последова­тельности инструкций, вводимых пользователем. Таким же образом, как это делают, например, РНР и Python. Это противоположно таким языкам программирования как С, где программа сначала компилируется и лишь затем запускается на выполнение. Также как и в Python, вы можете вводить команды GNU Octave в командной строке. Вы увидите много примеров чуть позже.

GNU Octave названа в честь химика Octave Levenspiel и не имеет ничего общего с музыкой и гармоническими колебаниями. Проект был начат James В. Rawlings и John G. Ekerdt, но в основном был разработан John W. Eaton, кто внес огромный вклад в этот проект. GNU Octave является официальным проектом GNU project (отсю­да приставка GNU), а код программы реализован в рамках GNU General Public License (GPL).

Это значит, что вы можете использовать программу для любых целей, копиро­вать и распространять ее, делать любые изменения в программе какие вы хотите. Прочитайте подробно лицензионное соглашение на сайте http://www.gnu.org/software/ octave/license, html.

В дальнейшем для удобства мы будем называть GNU Octave просто Octave. Тем не менее, если вы хотите, чтоб вас считали Octave гуру, используйте приставку "GNU"!

Применения

Как мы упоминали выше, Octave можно использовать для решения широкого круга различных научных проблем. Например, многие коммерческие компании, специализи­рующиеся на проблемах оптимизации, в частности упаковки контейнеров на больших торговых судах. Эти задачи могут формулироваться в терминах линейного програм­мирования, что требует решения больших систем линейных уравнений, с чем отлично справляется Octave. Вычислительный цент в Питтсбурге использует Octave для реше­ния задач уязвимости социальных номеров.

В исследовательских кругах, Octave используется для анализа данных, обработки изображений, эконометрики, статистического анализа и многого другого. В дальнейшем мы рассмотрим различные примеры такого использования.

Ограничения Octave

Octave создавалась, в основном, для проведения численных вычислений и не является программным языком общего назначения, таким как С или С++ Тем не менее, Octave имеет чрезвычайно широкую функциональность.

Тот факт, что Octave использует интерпретатор, означает, что Octave должна снача­ла преобразовать инструкции в машинный код для их выполнения. Это имеет как свои преимущества, так и свои недостатки. Основное преимущество состоит в том, что ин­струкции (команды) достаточно легко выполнить и изменить, не используя длительный процесс редактирования, компиляции и запуска, и позволяют программисту и поль­зователю контролировать процесс. Основной недостаток состоит в относительно мед­ленном выполнении программы по сравнению с предварительно откомпилированными программами, написанными на таких языках, как С или Fortran.

Тем не менее, как вы убедитесь, прочтя книгу, Octave в состоянии решать очень сложные и требовательные к вычислительным возможностям задачи, используя всего лишь несколько инструкций или команд с хорошей скоростью. Последняя глава книги познакомит вас с некоторыми механизмами оптимизации и возможностями использо­вания программ на С++ совместно с Octave для увеличения в некоторых ситуациях скорости вычислений.

Octave не рассчитана для выполнения аналитических (или символьных) математиче­ских вычислений. Она не является лучшим выбором, если вы хотите найти производную функции, скажем f(x) = х2. В этом случае такие программы как Maxima и Sage бу­дут более полезны. Следует отметить, что для Octave существуют пакеты расширений, которые производить основные аналитические математические операции.

Octave и MATLAB

Здесь самое место упомянуть MATLAB. Часто об Octave говорят как о клоне MATLAB. Скорее Octave пытается быть совместима с MATLAB. Тем не менее, будьте осторожны, в некоторых случаях вы не можете просто запустить вашу программу Octave в MATLAB и наоборот. В этой книге мы отметим, где могут встретиться проблемы совместимо­сти, однако мы будем говорить об Octave и не будем прилагать особых усилий для совместимости наших примеров с MATLAB.

Сообщество Octave

Новейшую версию Octave вы можете найти на странице http://www.octave.org. Здесь же вы найдете официальное руководство, Wiki страницу, советы по работе, последние новости, короткую историю программы и другие полезные сведения. На этой страни­це вы можете присоединиться к списку рассылке, для этого вам нужно иметь лишь email адрес. Сообщество пользователей очень активно и доброжелательно, и даже раз­работчики программы ответят на вопросы "простых" пользователей.

В дополнение к стандартному дистрибутиву Octave существует большое число дополнительных паке­тов (расширений), существенно расширяющих число функций и команд. Многие из них можно скачать со страницы Octave-Forge http://octave.sourceforge.net. Здесь вы найдете пакеты, специально созданные для обработки изображений, эконометрики, информа­ционной теории, аналитической математики и многие другие. После прочтения книги и выполнения заданий в конце каждой главы вы будете в состоянии написать ваш соб­ственный пакет расширения Octave. Вы можете поделиться вашей работой с остальным сообществом Octave, которое будет только благодарно вам за ваши усилия, а кто-то мо­жет даже расширить и улучшить вашу работу!

Установка Octave

Octave первоначально создавалась для работы в GNU/Linux. Тем не менее, вы може­те использовать ее и в Windows. Процедура установки в Windows проходит довольно гладко. Давайте с этого и начнем.

    Windows

Установка Octave в Windows довольно проста. Нужно пройти несколько этапов:

1. Зайдите на сайт Octave-Forge. Здесь вы найдете гиперссылку на инсталляционную программу для Windows. Скачайте этот инсталлятор на рабочий стол или другое место по вашему выбору.

2. Запустите инсталлятор двойным щелчком на его значке.

3. Вы увидите окно приветствия. Нажмите на кнопку Next.

4. В следующем окне вы увидите лицензионное соглашение, прочтите его. Нажмите на кнопку Next.

5. Теперь вы имеете возможность выбрать место, куда вы хотите установить Octave. Путь, предлагаемый по умолчанию, вполне подойдет. Когда вы выберите путь установки, нажмите на кнопку Next.

6. На следующем окне вам необходимо сделать выбор между различными версия­ми численных библиотек FFTW3 и ATLAS, которые Octave использует для вы­полнения Фурье преобразований и задач линейной алгебры. Различные версии специально созданы для разных архитектур CPU. Вы можете также выбрать до­полнительные пакеты, которые считаете необходимыми для ваших задач, как по­казано на скриншоте. Давайте пока не беспокоиться о деталях FFTW3 и ATLAS библиотек, а выберем generic versions.

7. Выберите для установки все дополнительные пакеты. Нажмите на кнопку Next и Octave будет установлена.

8. После установки вы можете прочитать файл README. Нажмите на кнопку Next. Вот и все - Octave установлена!

Обратите внимание, что интерактивное окружение Octave (the Octave prompt) мо­жет быть запущено после окончания установки. Для его закрытия наберите:

octave:1> exit

или нажмите Ctrl + D одновременно. Сочетание Ctrl + D является стандартной ко­мандой UNIX и часто используется для завершения работы программ в UNIX-системах, таких как GNU/Linux.

Если вы установили в Windows Octave версии 3.2.4, рекомендуется удалить пакет oct2mat. Этот пакет препятствует правильной работе графического окна программы. Например, когда вы строите график, он не появляется в графическом окне. Этого не происходит в GNU/Linux.

 GNU/Linux

В большинстве дистрибутивов GNU/Linux, Octave является частью системы. Поэтому перед установкой Octave, проверьте не установлена ли она уже на вашем компьютере. Чтобы это сделать, откройте терминал и наберите:

octave

Если Octave соответствующим образом установлена, вы увидите приглашение Octave и командную строку. Выйдите из программы набрав:

octave:1> exit

Или нажмите CTRL + D.

Если Octave не установлена, вы можете использовать менеджер пакетов вашего дис­трибутива. Например в Ubuntu вы можете использовать Synaptic Package Manager, ко­торый является графическим инструментом для установки и удаления софта на вашем компьютере. В случае Fedora и CentOS вы можете использовать YUM.

Удостоверьтесь, что будет установлена и программа для построения графиков, на­пример, gnuplot.

Установка Octave из исходных кодов в GNU/Linux

Если для вашей системы нигде нет готовых пакетов, то программу можно собрать (скомпилировать) самому из исходных кодов. Для того, чтобы установить Octave из исходных кодов, вам необходимо иметь:

• Утилиту GNU make

• Fortran и C/C++ компилер (GNU Compiler Collection (GCC) версии 4.1 или выше будет вполне достаточно)

• gnuplot

К счастью, эти программные пакеты обычно присутствуют в большинстве дистри­бутивов GNU/Linux.

Время действовать — установка из исходных кодов

Выполните последовательно следующие действия:

1.Загрузите последнюю стабильную версию Octave с сайта http://www.gnu.org/ software/octave/download.htm и сохраните в любом удобном месте. Программа заархивирована в файл с расширением .tar.gz.

2. Откройте терминал и откройте папку, куда вы загрузили исходник. Для разархивирования файла наберите:

tar zxf octave-version.tar.gz

3. Здесь version обозначает номер версии. Эта команда создаст папку octave-version.

4. Перейдите в эту папку набрав:

cd octave-version

5. Теперь мы можем сконфигурировать процесс компиляции и установки программы набрав:

./configure

6. Если конфигурационный процесс прошел успешно, мы можем перейти к компи­ляции кода Octave: make

7. Перед тем как начать установку, проверьте результат компиляции:

make check

8. Некоторые из тестов могут выдать ошибку. Тем не менее, это не значит, что ком­пиляция прошла неудачно. Тестирование не является обязательной процедурой.

9. Для установки Octave на компьютер вам необходимы права администратора (root). Например, вы можете использовать команды:

 sudo make install

10. Теперь введите пароль администратора в строке приглашения. Вот и все!

Что же произошло?

Как вы могли видеть, мы выполнили стандартную процедуру инсталляции в UNIX: конфигурирование, компиляцию, установку (configure, make, make install). Если вы не имеете привилегий администратора, вы не сможете установить Octave. Но вы можете, по крайней мере запустить Octave из папки bin/ в инсталляционном каталоге.

Напомним, что указанная процедура установит только Octave, но не программу по­строения графиков. Вам придется сделать это самостоятельно, иначе Octave не будет работать надлежащим образом.

Проверка установки

Настало время опробовать Octave! Существует несколько способов запуска интерпре­татора Octave. Один из них состоит в запуске сценария (скрипта) Octave, а другой - в запуске интерактивного окружения Octave, что мы и сделаем сейчас.

Время действовать — тестирование Octave

1. Вы можете запустить интерактивное окружение набрав octave в командной стро­ке в GNU/Linux, или двойным щелчком на значке Octave в Windows. Вы должны увидеть приглашение Octave:

octave:1>

2. Вы уже знаете, как выйти из интерактивного окружения Octave - просто набрав команду exit или нажав Ctrl + D, но мы не будем делать это сейчас!

3. В строке после приглашения наберите:

octave:1> surf(peaks)

4. Вы должны увидеть график трехмерной поверхности, как показано на левом рисунке ниже. Если этого не произойдет, значит инсталляция программы была неудачной. Сейчас установите указатель мыши на графическое окно и нажав ле­вую кнопку подвигайте указатель. Если ваша программа построения графиков поддерживает эту процедуру поверхность будет вращаться. Если вы щелкнете третьей кнопкой мыши (колесом) на графическом окне, вы сможете увеличить график двигая указатель из стороны в сторону или сверху вниз.

5. Давайте построим контурный график. Наберите:

octave:2> contourf(peaks)

6.Выглядит ли ваш график так как на рисунке справа? Если нет, то это может быть связано с тем, что вы используете Octave версии 3.2.4 с загруженным пакетом oct2mat. Попробуйте набрать

octave:3> pkg unload oct2mat

7. Теперь повторите предыдущую команду.

8. Щелкнете третьей кнопкой мыши где-либо внутри графического окна. Если вы используете gnuplot появится крестик и два числа. Крестик указывает место, на котором вы щелкнули, а числа - координаты х и у этой точки.

Что же произошло?

Рисунок слева - график математической функции, которая является скалярной функ­цией двух переменных у и х вида:

Значения функции определяются в Octave командой peaks, которая является име­нем для функции f. Затем строиться график поверхности с помощью функции Octave surf. По умолчанию Octave использует для вычислений f диапазон из 50 значений х и у в интервале [-3; 3]. Как вы уже догадались, функция contourf Octave строит кон­турный график функции f. В дальнейшем мы рассмотрим как добавить к графику наименования осей, текст и многое другое.

Обратили ли вы внимание на фразу "функция Octave"? Функция Octave не обяза­тельно математическая функция, такая как в уравнении, она может выполнять множество различных типов операций. Пока не обращайте на это много внимания, мы обсудим функции Octave functions чуть позже.

Обратите внимание, что интерпретатор сохраняет ряд введенных команд в своем окне.

   Настройка Octave

При старте интерпретатор Octave считывает несколько конфигурационных файлов. Эти файлы могут быть изменены, чтобы добавить системные пути, изменить вид пригла­шения командной строки Octave, редактор и многое другое. Изменения могут быть глобальными и затрагивать всех пользователей Octave, использующих данный компью­тер. Или направлены на работу с определенной версией Octave, отдельным проектом или пользователем.

 Конфигурационные файлы называются или octaverc или .octaverc. в зависимости от того где они расположены и как влияют на конфигурацию Octave. Они обычно состоят из последовательности команд Octave, так что вы можете выпол­нить их и из командной строки интерпретатора Octave. Это удобно для тестирования конфигурации до внесения изменений в файлы octaverc или .octaverc.

Имена octaverc и .octaverc, естественно, не поддерживаются в MATLAB. Тем не менее, поддерживаются большинство команд. Поэтому можно скопировать содержимое конфигурационных файлов Octave в файл startup.m MATLAB.

В Windows у пользователя нет домашней папки, эквивалентной домашней папке в GNU/Linux. Поэтому рекомендуется создать такую папку для домашней директории Octave. Вы можете затем дать команду Octave перейти в эту папку и загрузить из нее конфигурационный файл, независимо от того откуда вы запустили интерпретатор.

Если вы используете GNU/Linux, можно пропустить следующий раздел "Время дей­ствовать".

Время действовать — создание домашней папки

Предположим, что домашней директорией Octave является C:\Documents_and_Settings\GNU OctaveV Мы можем создать эту директорию прямо из Octave.

1. Запустите Octave и введите следующие команды:

octave:1> cd С:

octave:2> cd "Documents and Settings"

octave:3> mkdir "GNU Octave"

 ans = 1

2. Ответ ans = 1 после введения последней команды означает, что директория успеш­но создана. Если Octave возвращает 0, значит произошла какая то ошибка, сооб­щение о которой Octave выведет на экран. Вместо создания директории в Octave, вы можете сделать это и в Windows Explorer.

3. Необходимо указать, что это будет домашняя директория Octave. Давайте сделаем это из Octave:

octave:4> edit

4. Вы должны увидеть окно редактора. Редактором по умолчанию в Windows явля­ется Notepad++. Откройте в нем файл

c:\octave-home\share\octave\site\m\startup\octaverc, где octave-home путь, куда была установлена Octave, например, 0ctave\3.2.4_gcc-4.4.0. Добавьте сле­дующие строки в конце файла.

setenvOHOME',  'C:\Document and Settings\GNU OctaveV); cd ~/

5. Сохраните файл, закройте редактор и перезапустите Octave. Это все!

 Что же произошло?

Первые три команды Octave вполне ясны: мы переходим в директорию С: \Documents_and_Settings\ и создаем директорию GNU_0ctave. После этого мы от­крываем файл глобальной конфигурации и добавляем две строки. При следующем запуске Octave выполнит эти команды. Первая инструкция сообщает интерпретатору установить в качестве рабочей директории

C:\Document_and_Settings\GNU_Octave\, а вторая осуществляет переход в нее.

Создание вашего первого файла .octaverc

Установив домашнюю директорию Octave в Windows, мы можем настроить Octave. Сделать это можно в Windows b GNU/Linux одинаковым образом.

Время действовать — редактирование .octaverc

  1.Запустите Octave, если вы этого еще не сделали, и откройте редактор по умолча­нию:

octave:1> edit

          2.Скопируйте следующие строки в файл и сохраните его как . octaverc в домаш­ней директории Octave в Windows, или в домашней директории пользователя в GNU/Linux. Вы можете сделать это и просто в редакторе без использования Octave.

PS1 ("» ");

edit mode "async"

Закройте редактор и перезапустите Octave. Изменился ли вид приглашения Octave? Оно должно выглядеть как »

Вместо перезапуска Octave каждый раз, когда вы делаете изменения в вашем конфигурационном файле, вы можете выполнить команду octave: 1> source (". octaverc"). которая прочитает все команды из файла.

Что же произошло?

PS1("» ") устанавливает новый вид приглашения командной строки Octave. Вы мо­жете заменить его на любой другой. Для расширения предыдущего примера можно использовать PS1("\\#» "), что добавит счетчик команд перед ». Вы можете прове­рить, какой вид вам больше подходит прямо в командной строке без редактирования файла .octaverc. Далее мы будем использовать вариант по умолчанию \\s:\\#>.

Команда edit mode "async" необходима для обеспечения возможности работы в командной строке Octave не закрывая редактор.

   Дополнительно о .octaverc

Редактор по умолчанию может быть также установлен в . octaverc. Это можно сделать добавив строку в ваш файл .octaverc

edit editor name of the editor

где name of the editor имя вашего редактора. Вы можете выбрать notepad если вы используете Windows, или gedit в GNU/Linux. Перед добавлением изменений в файл .octaverc, вы можете проверить, работает ли новый редактор из командной строки Octave.

Позднее мы напишем файлы скриптов и функций. Octave должна быть проинструк­тирована, где искать эти файлы. Octave использует иерархию путей поиска, и крайне важно понять, как научить Octave искать эти файлы в определенных директориях. Ре­комендуется создать новую директорию octave в вашей домашней папке (домашней папке Octave в Windows). Вы сможете помещать ваши файлы Octave в эту папку и указать интерпретатору искать их здесь.

Давайте сначала создадим эту директорию. Проще всего запустить Octave и ввести:

octavel:> cd ~/ octave2:> mkdir octave

Что делают эти команды вполне очевидно. Теперь запустим редактор:

octave3:> edit .octaverc

и добавим следующую строку в файл .octaverc: addpath(""/octave");

Сохраним файл, закроем редактор и перезапустим Octave, или выполним команду source(".octaverc"). В командной строке Octave введите:

octavel:> path

Теперь вы должны увидеть, что путь ~/octave/ добавлен в список поиска. В Windows этот путь будет добавлен для всех пользователей. Список путей поиска может быть длинным, так что вы можете посмотреть его весь, используя стрелки клавиатуры. Когда вы достигнете конца списка, нажмите Q для возврата в командную строку Octave.

   Установка дополнительных пакетов

Как уже упоминалось, существует большое число дополнительных пакетов Octave, большинство из которых можно загрузить со страницы Octave-Forge. Octave имеет ве­ликолепный инструмент для установки и удаления этих пакетов. Давайте попытаемся установить пакет msh, который используется для создания сеток для решения диффе­ренциальных уравнений.

Время действовать — установка пакетов

1. Перед установкой нового пакета посмотрите, какие пакеты уже установлены и проверьте их версии. Запустите Octave, если вы еще это не сделали. Введите ко­манду:

octave:1> pkg list

2. Вы должны увидеть таблицу с именами установленных пакетов, номера версий и директории их установки. Например:

Package Name I Version I  Installation directory

combinatorics  I  1.0.6 I /octave/packages/combinatorics-1.0.6

3. Если при установке Octave в Windiws вы выбрали установку всех пакетов, список может быть очень длинным. Просмотрите его, не установлен ли уже пакет msh, и если да, то какова его версия. Для возвращения в командную строку нажмите Q.

4. Теперь зайдите на страницу Octave-Forge, найдите пакет msh и посмотрите его описание (Details) справа от имени пакета. Вы увидите окно с описанием паке­та как показано на рисунке. Убедитесь, что версия пакета выше, чем у пакета, уже установленного. (Если нет, вернитесь назад, расслабьтесь и просто прочти­те дальнейшее.) В описании пакета указано, что он зависит от пакета spline. Естественно, если пакет spline не установлен в вашей системе, нам потребуется установить сначала его. Загрузите оба пакета msh и spline в вашу домашнюю директорию Octave. (Между прочим, проверьте, не зависит ли пакет spline от других пакетов). Загруженные файлы заархивированы в файлы с расширением .tar.gz. Для установки пакетов наберите в командной строке Octave:

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

5. Перед этим убедитесь, что вы загрузили файлы в домашнюю папку Octave.

6. Для проверки вашего нового списка пакетов введите:

octave:4> pkg list

combinatorics I 1.0.6 I /octave/packages/combinatorics-1.0.6 msh

7. Вы можете получить описание пакета msh в Octave с помощью команды:

octave5:> pkg describe msh

Package name: msh

Short description:

Status:

Not loaded

8. Из статуса вы можете видеть, что пакет не загружен. Это значит, что вы не можете использовать его возможности. Для загрузки пакета наберите:

octave:6> pkg load msh

9. Проверьте, действительно ли пакет загрузился, используя команду pkg describe msh. выгрузить пакет можно с помощью команды:

octave:7> pkg unload msh

Что же произошло?

Наиболее важные детали уже подробно объяснены. Заметьте, что пакет splines должен быть установлен раньше msh из-за зависимостей.

Вам может показаться странным, что пакет сначала нужно загрузить в Octave перед его использованием. Пакет мажет загру­жаться и автоматически если вы установили его с опцией -auto. Например, команда 3 может быть заменена на:

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

Некоторые пакеты будут автоматически загружаться даже если вы специально не указывали это при их установке. Вы можете воспрепятствовать этому используя ко­манду при установке.

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

Удаление пакетов

Удалить пакет так же просто как и установить:

octave:8> pkg uninstall msh

Заметьте, что вы получите сообщение об ошибке, если попытаетесь удалить пакет splines перед удалением msh из-за их зависимостей.

   Получение помощи

Команда pkg очень гибкая и может быть вызвана с различными опциями. Вы можете посмотреть их все с помощью команды:

octave:9> help pkg

Для команды pkg документация довольно  обширна. Вы можете перемещаться по тексту с помощью клавиш F и В. В любой момент вы можете прервать просмотр и вернуться в командную строку Octave с помощью клавиши Q. Предыдущий пример ил­люстрирует справку для команды pkg. Справка доступна и для других команд Octave. Вы можете попробовать посмотреть, например справку для PS1.

Поведение командной строки Octave

Часто вы будете использовать одни и те же команды во время сессии Octave. Иногда вы можете забыть имя определенной команды или вы помните лишь несколько первых букв команды. Octave может помочь вам. Например, вы можете увидеть предыдущие команды используя стрелки вверх и вниз (Попробуйте!). Octave даже сохраняет коман­ды из предыдущих сессий.

Например, если вы хотите изменить внешний вид пригла­шения командной строки, наберите:

octave:10> PS <up arrow key>

Теперь будут показаны только команды, начинающиеся с PS show up. Вместо исполь­зования стрелок, попробуйте нажать табулятор дважды:

octave:11> PS

(Теперь нажмите TAB дважды) PS1 PS2 PS4

Вы увидите все существующие команды (и функции), имеющие приставку PS.

 Выводы

• В этой главе вы узнали следующее:

• О Octave, ее достоинствах и недостатках.

• Как установить Octave в Windows и GNU/Linux.

• Как проверить установку с помощью peaks.

• Как использовать и изменить редактор по умолчанию.

• Как настроить Octave. Например, мы увидели, как изменить вид приглашения командной строки и как добавить пути поиска.

• Как использовать команду pkg для установки и удаления дополнительных паке­тов.

• Как использовать утилиту help.

Сейчас мы готовы двигаться дальше и обсудить типы данных и операторы Octave.