Как установить octave под windows
Assuming a package is available in the file image-1.0.0.tar.gz it can be installed from the Octave prompt with the command
If the package is installed successfully nothing will be printed on the prompt, but if an error occurred during installation it will be reported. It is possible to install several packages at once by writing several package files after the pkg install command. If a different version of the package is already installed it will be removed prior to installing the new package. This makes it easy to upgrade and downgrade the version of a package, but makes it impossible to have several versions of the same package installed at once.
To see which packages are installed type
In this case only version 1.0.0 of the image package is installed. The ‘*’ character next to the package name shows that the image package is loaded and ready for use.
It is possible to remove a package from the system using the pkg uninstall command like this
If the package is removed successfully nothing will be printed in the prompt, but if an error occurred it will be reported. It should be noted that the package file used for installation is not needed for removal, and that only the package name as reported by pkg list should be used when removing a package. It is possible to remove several packages at once by writing several package names after the pkg uninstall command.
To minimize the amount of code duplication between packages it is possible that one package depends on another one. If a package depends on another, it will check if that package is installed during installation. If it is not, an error will be reported and the package will not be installed. This behavior can be disabled by passing the -nodeps flag to the pkg install command
Since the installed package expects its dependencies to be installed it may not function correctly. Because of this it is not recommended to disable dependency checking.
: pkg command pkg_name : pkg command option pkg_name : [ out1 , …] = pkg ( command , … )
Manage or query packages (groups of add-on functions) for Octave.
Different actions are available depending on the value of command and on return arguments.
Install named packages. For example,
installs the package found in the file image-1.0.0.tar.gz .
The option variable can contain options that affect the manner in which a package is installed. These options can be one or more of
The package manager will disable dependency checking. With this option it is possible to install a package even when it depends on another package which is not installed on the system. Use this option with care.
A local installation (package available only to current user) is forced, even if the user has system privileges.
A global installation (package available to all users) is forced, even if the user doesn’t normally have system privileges.
Install a package directly from the Octave-Forge repository. This requires an internet connection and the cURL library.
Security risk: no verification of the package is performed before the installation. There are no signature for packages, or checksums to confirm the correct file was downloaded. It has the same security issues as manually downloading the package from the Octave Forge repository and installing it.
The package manager will print the output of all commands as they are performed.
Check installed Octave-Forge packages against repository and update any outdated items. This requires an internet connection and the cURL library. Usage:
Uninstall named packages. For example,
removes the image package from the system. If another installed package depends on the image package an error will be issued. The package can be uninstalled anyway by using the -nodeps option.
Add named packages to the path. After loading a package it is possible to use the functions provided by the package. For example,
adds the image package to the path.
Remove named packages from the path. After unloading a package it is no longer possible to use the functions provided by the package.
Show the list of currently installed packages. For example,
will produce a short report with the package name, version, and installation directory for each installed package. Supply a package name to limit reporting to a particular package. For example:
If a single return argument is requested then pkg returns a cell array where each element is a structure with information on a single package.
If two output arguments are requested pkg splits the list of installed packages into those which were installed by the current user, and those which were installed by the system administrator.
The «-forge» option lists packages available at the Octave-Forge repository. This requires an internet connection and the cURL library. For example:
Show a short description of installed packages. With the option «-verbose» also list functions provided by the package. For example,
will describe all installed packages and the functions they provide. Display can be limited to a set of packages:
If one output is requested a cell of structure containing the description and list of functions of each package is returned as output rather than printed on screen:
If any of the requested packages is not installed, pkg returns an error, unless a second output is requested:
flag will take one of the values «Not installed» , «Loaded» , or «Not loaded» for each of the named packages.
Set the installation prefix directory. For example,
sets the installation prefix to
/my_octave_packages . Packages will be installed in this directory.
It is possible to get the current installation prefix by requesting an output argument. For example:
The location in which to install the architecture dependent files can be independently specified with an addition argument. For example:
Set the file in which to look for information on locally installed packages. Locally installed packages are those that are available only to the current user. For example:
It is possible to get the current value of local_list with the following
Set the file in which to look for information on globally installed packages. Globally installed packages are those that are available to all users. For example:
It is possible to get the current value of global_list with the following
Build a binary form of a package or packages. The binary file produced will itself be an Octave package that can be installed normally with pkg . The form of the command to build a binary package is
where builddir is the name of a directory where the temporary installation will be produced and the binary packages will be found. The options -verbose and -nodeps are respected, while all other options are ignored.
Rebuild the package database from the installed directories. This can be used in cases where the package database has been corrupted.
Octave for Microsoft Windows
Users are encouraged to use the latest version unless a specific feature or requirement warrants using an older version of the software. Version specific instructions and installation notes are provided below.
Note: As of version 4.4.1, Octave no longer supports Windows XP. There may be some workarounds to get Octave installed and running in command line mode (see Bug #54662), but maintainers cannot provide support and troubleshooting for this beyond what has already been documented.
Contents
Installers for Microsoft Windows [ edit ]
The easiest way to install GNU Octave on Microsoft Windows is by using MXE builds. For the current release, both 32-bit and 64-bit installers and zip archived packages (.zip and .7z formats) can be found at https://www.gnu.org/software/octave/download.html under the Windows tab.
- For executable (.exe) installers: the user can simply run the downloaded file and follow the on-screen installation prompts. It is recommended that the installation path does not include spaces or non-ASCII characters. Shortcuts to the program will be created automatically.
- For the 7z/zip archives:
- Extract the file content to a directory on the harddrive (such as C:\Octave ). Spaces or non-ASCII characters in the path are discouraged and may cause program errors.
- Manually create a shortcut to the octave.vbs file in the main installation directory. (Right-click on the file, select ‘Create Shortcut’, and move the new shortcut to your desired location.)
- If a command-line only instance of Octave is desired, the user can create another shortcut as stated above, right-click on the shortcut, select Properties, and add —no-gui to the end of the Target field.
- IMPORTANT: Run the post-install.bat file before running Octave the first time to reduce plot delays due to the Windows font cache and make the pre-installed packages visible to the system.
Packages [ edit ]
A selection of pre-built, Octave Forge packages are included with for all versions of the official Windows release. If you followed the installation directions above you can confirm the package list by typing the command below at the Octave command prompt:
A typical output (for version 5.2.0) is:
(__OH__) refers to the location of the OCTAVE_HOME environment variable.
If Octave was installed from a zip of 7z archive and you did not run the post-install.bat file, you may need to run:
All packages can be updated to the latest version by running:
Other packages can be installed by running:
To install a new or updated package version manually, the package file can be downloaded from the Octave Forge website to the working directory and can be installed using:
Высшая математика командной строки — GNU Octave
Как я и обещал, перехожу от обзора программ замены калькулятора к более серьезным инструментам. Если помните схему из предыдущего поста, то во второй категории находились табличные: OpenOffice / LibreOffice сотоварищи. Эту партию мы можем смело пропустить, так как к командной строке она не относится, к тому же, среди читателей Хабра трудно найти человека, который бы в них не разбирался. Поэтому перехожу сразу к третьей категории.
Специализированные математические программы, уровень студент+
На первом месте в этом списке находится Octave , и это не случайность. Исследователи из Университета Мэриленда в США провели сравнительный анализ математических вычислений, используя MATLAB, Octave, SciLab и FreeMat в простом сценарии и в сложном. В первом случае решали систему линейных уравнений а в втором — конечно-разностную дискретизацию уравнения Пуассона в двухмерном пространстве. Основной вывод — GNU Octave справляется с задачами лучше остальных открытых математических пакетов, демонстрируя результат (страницы 23 и 25) сопоставимый с матлабовским.
Но сначала немного исторического контекста, чтобы понять, как закалялись математические программы с открытыми исходниками.
Догнать и перегнать MATLAB
Так сложилось, что коммерческие программы прибежали и первыми застолбили поляну математических вычислений. Уже с конца 1970-х гг. создатель языка программирования Клив Моулер распространяет MATLAB в университетах США, а в 1984-м вместе с двумя компаньонами переписывают его с Фортрана на Си и создают компанию The MathWorks. Примечательно, что ранние версии распространялись с открытым исходным кодом.
Это было-было, а MATLAB , каким мы его знаем сегодня — это ЯП высокого уровня с поддержкой 2D / 3D графики, разнообразными математическими функциями, интерактивной средой программирования, численных расчетов и решения задач. Внешние интерфейсы позволяют ему интегрироваться со сторонними приложениями и языками программирования. Более 1 000 000 инженеров и ученых по всему миру используют MATLAB и платят за это солидную денежку.
С большим опозданием в игру включаются программы с открытыми исходниками. Только в 1990-х появляются математические пакеты GNU Octave, Scilab и вступают в конкуренцию с лидером вычислительного программирования.
Задуманный изначально как программное пособие для проектирования химического реактора и названный в честь профессора химии Октава Левеншпиля, преподававшего автору математического пакета, Octave призван был заменить студентам Техасского Университета сложный в отладке Fortran . Версия 1.0 вышла в свет 17 февраля 1994 г. Проект стабильно развивается, и в июле нынешнего года зарелизился Octave 4.0.3 . Ждем ебилдов .
Основной миссией Octave была, и в обозримом будущем скорее всего так и останется, быть годной заменой MATLAB так же, как OpenOffice/LibreOffice замещает MS Office для тех, кто умеет считать копейку. Собственно, для этого Octave имеет совместимый с MATLAB синтаксис и набор функций. Более того, несовместимость с MATLAB считается багом, однако софтверная Фемида уже имеет подобный прецедент, и это не считается нарушением копирайта. В этой связи, можно считать Octave программным клоном. Правда о полной совместимости пока говорить не приходится, но работа в этом направлении не прекращается.
Octave написан на C++ , используя стандартную библиотеку шаблонов, имеет интерактивный командный интерфейс, поддерживает расширения — динамически загружаемые модули на родном языке или на C, C++, Fortran и др. Так же как и MATLAB , в алгебраических вычислениях Octave использует библиотеки Basic Linear Algebra Subroutines (BLAS) и Linear Algebra Package (LAPACK).
Установка
Установка Octave в Linux ничем не отличается от установки других программ. На Gentoo Linux запускаем:
Дебианщики делают то же самое с помощью apt .
Для SUSE и Arch тоже все очень просто, а вот пользователям Красной Шапки и CentOS придется чуток повозиться. Попытка установить Octave легким движением кисти завершается ошибкой, пакет в репозитариях не найден.
Благо, есть обходной путь. Нужно сперва установить пакет epel-release.
И только после этого yum install octave сработает.
Наконец, все готово и программа установлена.
Операции с матрицами
Не будем терять время и делать операции, которые можно повторить с помощью bc и awk , о ктоторых речь шла в прошлый раз. Поиграемся немного с матрицами.
Сперва простое транспонирование матрицы:
Попробуем решить систему линейных уравнений:
Вбиваем матрицу A, вектор b и решаем уравнение Ax = b в матричном виде
Находим детерминант и собственные значения матрицы.
Комплексные числа тоже поддерживаются в вычислениях.
Функции и переменные
В Octave переменные и функции создавать гораздо проще, чем, к примеру, в Java или C. На примере матриц, мы уже видели как объявлять переменные. Создания новой функции имеет следующий синтаксис
Как правило, новую функцию создают либо в отдельном файле, либо в скрипт-файле Octave
до первого ее вызова. Если предполагается использовать пользовательскую функцию в разных скрипт-файлах, то, конечно, предпочтительно создать ее в отдельном файле. В GNU Octave файлы с функциями имеют расширение .m и загружаются автоматически. Имя файла должно строго совпадать с именем функции.
Напишем функцию для решения квадратичного уравнения ax² + bx + c = 0
Графический интерфейс
Вообще-то, мы тут за математику командной строки гутарим, но пока непонятно как вывести на экран график функции. Впрочем, никакого секрета тут нет — для этих целей используется Gnuplot . Так можно изобразить Аттрактор Лоренца, установив дополнительный пакет odepkg .
Наиболее удобной графической оболочкой для работы с Octave является программа QtOctave . Последняя уже стабилизировалась и включена в состав пакета с момента выхода Octave 4.0 .
Что-же дальше?
Может возникнуть вопрос: а зачем вообще нужны открытые математические пакеты? Офисные приложения нужны всем, но ведь далеко не каждому необходимо сидя дома решать уравнения Пуассона, с помощью преобразования Лапласа. Для ВУЗ-ов MATLAB стоит значительно дешевле, нежели для физических лиц и коммерческих организаций. Коммерческие организации, если будет нужно, найдут денежные средства, а обычные люди пусть занимаются математикой в университетах или считают столбиком.
Конечно же, это ошибочное мнение. Научные расчеты, выполненные с использованием открытого ПО имеют дополнительный «уровень защиты», ведь при желании любой может повторить прогнать те же самые расчеты и проверить валидность результатов. Те же самые вычисления, выполненные на дорогущем ПО, частично отсекают возможность проверки результатов. Проблема на самом деле гораздо шире (английский текст) и дело не только в открытых или проприетарных математических программах. Не секрет, что научные журналы как правило не требуют от авторов предоставить данные и методику, достаточные для гарантированного повтора результатов эксперимента, проверки модели. Особенно часто этим грешат экономисты и финансисты, попросту засекречивая свои данные. Проверка расчетов и выводов среди выборки из массива статей с «засекреченными» данными дала неожиданные результаты (английский текст). Наука, как и софт, должна быть открытой, вот почему открытые математические пакеты имеют ценность для всего общества.
Рекомендуется к прочтению
Кроме последней книги, остальные материалы, использованные в статье, можно без труда найти в интернете. Половина из приведенных выше ссылок ведут на английские страницы. Буду рад вкратце сообщить о чем идет там речь или помочь с переводом.
- GNU Octave 4.0.1 Manual
- Алексеев Е.Р., Чеснокова О.В GNU Octave для студентов и преподавателей, 2011
- Н. Б. Шамрай Краткое руководство по работе с пакетами GNU Octave и Gnuplot, 2011
- Jesper Schmidt HansenGNU Octave