FAQ: Difference between revisions

Jump to navigation Jump to search
282 bytes removed ,  13 June 2019
m
m (→‎Octave-Forge: Overhaul section improve code example.)
(13 intermediate revisions by 4 users not shown)
Line 18: Line 18:


[https://www.gnu.org/software/octave/ GNU Octave] is a high-level interpreted language, primarily intended for numerical computations.  It provides capabilities for the numerical solution of linear and nonlinear problems, and for performing other numerical experiments.  It also provides extensive graphics capabilities for data visualization and manipulation.  GNU Octave is normally used through its interactive interface ([https://en.wikipedia.org/wiki/Command-line_interface CLI] and [https://en.wikipedia.org/wiki/Graphical_user_interface GUI]), but it can also be used to write non-interactive programs.  
[https://www.gnu.org/software/octave/ GNU Octave] is a high-level interpreted language, primarily intended for numerical computations.  It provides capabilities for the numerical solution of linear and nonlinear problems, and for performing other numerical experiments.  It also provides extensive graphics capabilities for data visualization and manipulation.  GNU Octave is normally used through its interactive interface ([https://en.wikipedia.org/wiki/Command-line_interface CLI] and [https://en.wikipedia.org/wiki/Graphical_user_interface GUI]), but it can also be used to write non-interactive programs.  
The GNU Octave language is quite similar to Matlab so that most programs are easily portable.
The GNU Octave language is quite similar to Matlab so that most programs are easily portable.


The GNU Octave distribution includes a [http://www.octave.org/octave.pdf 1000+ page Texinfo manual].  Access to the complete text of the manual is available via the <code>doc</code> command at the GNU Octave prompt.
The GNU Octave distribution includes a [http://www.octave.org/octave.pdf 1000+ page Texinfo manual].  Access to the complete text of the manual is available via the <code>doc</code> command at the GNU Octave prompt.


==What is Octave-Forge?==
==What is Octave Forge?==


[https://octave.sourceforge.io/ Octave-Forge] is a collection of [[packages]] for GNU Octave, something similar to the Matlab toolboxes.  When talking about the two projects at the same time, GNU Octave is usually referred to as Octave core (or just "core").  Octave-Forge also serves as a test bed for code that may eventually end up in the core, and distributes binaries for systems with a lack of developers tools (mainly Windows).
[https://octave.sourceforge.io/ Octave Forge] is a collection of [[packages]] for GNU Octave, something similar to the Matlab toolboxes.  When talking about the two projects at the same time, GNU Octave is usually referred to as Octave core (or just "core").  Octave Forge also serves as a test bed for code that may eventually end up in the core, and distributes binaries for systems with a lack of developers tools (mainly Windows).


==Who uses Octave?==
==Who uses Octave?==
Line 50: Line 50:
Octave is free software and does not legally bind you to cite it.  However, we have invested a lot of time and effort in creating GNU Octave, and we would appreciate if you would cite if you used.  To cite GNU Octave in publications use:
Octave is free software and does not legally bind you to cite it.  However, we have invested a lot of time and effort in creating GNU Octave, and we would appreciate if you would cite if you used.  To cite GNU Octave in publications use:


   John W. Eaton, David Bateman, Søren Hauberg, Rik Wehbring (2017).
   John W. Eaton, David Bateman, Søren Hauberg, Rik Wehbring ({{Release Year}}).
   GNU Octave version {{Release}} manual: a high-level interactive language for numerical computations.
   GNU Octave version {{Release}} manual: a high-level interactive language for numerical computations.
   URL https://www.gnu.org/software/octave/doc/v{{Release}}/
   URL https://www.gnu.org/software/octave/doc/v{{Release}}/
Line 59: Line 59:
     title    = {{GNU Octave} version {{Release}} manual: a high-level interactive language for numerical computations},
     title    = {{GNU Octave} version {{Release}} manual: a high-level interactive language for numerical computations},
     author    = {John W. Eaton and David Bateman and S{\o}ren Hauberg and Rik Wehbring},
     author    = {John W. Eaton and David Bateman and S{\o}ren Hauberg and Rik Wehbring},
     year      = {2017},
     year      = <span>{</span>{{Release Year}}},
     url      = {https://www.gnu.org/software/octave/doc/v{{Release}}/},
     url      = {https://www.gnu.org/software/octave/doc/v{{Release}}/},
   }
   }


Run <code>citation</code> at the Octave prompt for details on how to best cite the Octave version you are running.  Certain Octave packages also have recommended citations in which case use <code>citation package_name</code>.
Run {{manual|citation}} at the Octave prompt for details on how to best cite the Octave version you are running.  Certain Octave packages also have recommended citations in which case use <code>citation package_name</code>.


Note that there are two reasons for citing the software used.  One is giving recognition to the work done by others which we already addressed.  The other is giving details on the system used so that experiments can be replicated.  For this, you should cite the version of Octave and all packages used (you can get this information using the <code>ver</code> command), as well as any details of your setup as part of your Methods.  In addition, you should make your source available.  See [http://software.ac.uk/so-exactly-what-software-did-you-use How to cite and describe software] for more details and an in depth discussion.
Note that there are two reasons for citing the software used.  One is giving recognition to the work done by others which we already addressed.  The other is giving details on the system used so that experiments can be replicated.  For this, you should cite the version of Octave and all packages used (you can get this information using the <code>ver</code> command), as well as any details of your setup as part of your Methods.  In addition, you should make your source available.  See [http://software.ac.uk/so-exactly-what-software-did-you-use How to cite and describe software] for more details and an in depth discussion.
Line 69: Line 69:
==What documentation exists for Octave?==
==What documentation exists for Octave?==


Besides this wiki, the GNU Octave distribution includes a [http://www.octave.org/doc/interpreter 1000+ page Texinfo manual] ([http://www.octave.org/octave.pdf PDF]).  Access to the complete text of the manual is available via the <code>doc</code> command at the GNU Octave prompt.  If you have problems using this manual, or find that some topic is not adequately explained, indexed, or cross-referenced, please report it on http://bugs.octave.org.
Besides this wiki, the GNU Octave distribution includes a [http://www.octave.org/doc/interpreter 1000+ page Texinfo manual] ([http://www.octave.org/octave.pdf PDF]).  Access to the complete text of the manual is available via the {{manual|doc}} command at the GNU Octave prompt.  If you have problems using this manual, or find that some topic is not adequately explained, indexed, or cross-referenced, please report it on http://bugs.octave.org.


==How can I report a bug in Octave?==
==How can I report a bug in Octave?==
Line 134: Line 134:
For general use, it is recommended to use the latest stable version of Octave (currently {{Release}}), available from http://www.octave.org/download.html.  For development and bleeding-edge features one can obtain the development source code from the Mercurial repository https://hg.savannah.gnu.org/hgweb/octave/graph/.
For general use, it is recommended to use the latest stable version of Octave (currently {{Release}}), available from http://www.octave.org/download.html.  For development and bleeding-edge features one can obtain the development source code from the Mercurial repository https://hg.savannah.gnu.org/hgweb/octave/graph/.


The used version of Octave is available via the <code>ver</code> command and a list of user-visible changes since the last release is available via the <code>news</code> command at the GNU Octave prompt.
The used version of Octave is available via the {{manual|ver}} command and a list of user-visible changes since the last release is available via the {{manual|news}} command at the GNU Octave prompt.


==On what platforms does Octave run?==
==On what platforms does Octave run?==
Line 144: Line 144:
The latest version of the Octave source code (and older versions) is available from:
The latest version of the Octave source code (and older versions) is available from:


* http://www.octave.org/download.html
* https://www.octave.org/download.html
* https://ftp.gnu.org/gnu/octave/
* https://ftp.gnu.org/gnu/octave/


Line 213: Line 213:
* Many optimizations of the accumarray function
* Many optimizations of the accumarray function
* Sparse matrix indexing has been rewritten for speed
* Sparse matrix indexing has been rewritten for speed
* The pkg command now accepts a -forge option to pull packages directly from Octave-forge
* The pkg command now accepts a -forge option to pull packages directly from Octave Forge


==What's new in version series 3.2.X of Octave==
==What's new in version series 3.2.X of Octave==
Line 236: Line 236:
* [http://hg.savannah.gnu.org/hgweb/octave/file/83792dd9bcc1/etc/NEWS.3 NEWS.3] for the 3.X.Y series
* [http://hg.savannah.gnu.org/hgweb/octave/file/83792dd9bcc1/etc/NEWS.3 NEWS.3] for the 3.X.Y series


=Octave-Forge=
=Packages and Octave Forge=


== How do install or load all Octave-Forge packages? ==
==How do I install or load all Octave Forge packages?==


Do not do it!  Really, there is no reason to do this.  Octave has many packages for different needs and is unlikely that you need all of them.  You either have a small set of required packages, in which case
Do not do it!  Really, there is no reason to do this.  Octave has many packages for different needs and is unlikely that you need all of them.  You either have a small set of required packages, in which case
Line 253: Line 253:
</syntaxhighlight>
</syntaxhighlight>


== How do I automatically load a package at Octave startup? ==
==I have installed a package but still get a "foo undefined" error?==
 
You have probably forgotten to load the package.  Use {{Codeline|pkg load package-name}} to load it.  Most packages are no longer loaded automatically to avoid surprises.  See reasoning on related FAQ [[FAQ#How_do_I_install_all_Octave_packages.3F|how do I install all Octave packages]].  If you want a specific package to be loaded by default at startup, consider adding the {{Codeline|pkg load}} command on your {{path|[[.octaverc]]}} file.
 
==I cannot install a package. Octave complains about a missing mkoctfile.==
 
You should normally use your distribution's packages.  For Debian and Fedora, Octave package <code>foo</code> will be a deb or rpm called <code>octave-foo</code>, and you should install that instead using <code>apt</code> or <code>yum</code>.
 
If you really need to build Octave packages from source to install them, you'll need {{manual|mkoctfile}}. Most distributions split Octave into several packages.  The script {{manual|mkoctfile}} is then part of a separate package:
 
* Debian/Ubuntu: [https://packages.debian.org/stretch/liboctave-dev liboctave-dev]
 
* Fedora: {{Codeline|octave-devel}}
 
==How do I automatically load a package at Octave startup?==


When Octave starts, it runs the file {{Path|~/.octaverc}} (in your user's home directory).  If you want Octave to automatically load a package, simply add a <code>pkg load pkg-name</code> command to it.  If the files does not exist, create it.
When Octave starts, it runs the file {{Path|~/.octaverc}} (in your user's home directory).  If you want Octave to automatically load a package, simply add a <code>pkg load pkg-name</code> command to it.  If the files does not exist, create it.
Line 263: Line 277:
==How do I execute an Octave script?==
==How do I execute an Octave script?==


First of all, make sure you understand [http://www.gnu.org/software/octave/doc/interpreter/Script-Files.html the difference between script files and function files]. If you want to execute a function defined in a file, just call the function like any other Octave function: <code>foo(arg1, arg2);</code>
First of all, make sure you understand [http://www.octave.org/doc/interpreter/Script-Files.html the difference between script files and function files]. If you want to execute a function defined in a file, just call the function like any other Octave function: <code>foo(arg1, arg2);</code>


To execute a script from within Octave, just type its name without the .m extension. Thus, if you have a script called <code>foo.m</code>, just type <code>foo</code> from within Octave to execute it. You have to make sure that the script is in your current path. Type <code>path</code> in Octave to see what this path is, and type <code>pwd</code> to print the working directory (where you're currently standing). The current working directory is referred to as "." in the <code>path</code>.
To execute a script from within Octave, just type its name without the <code>.m</code> extension. Thus, if you have a script called <code>foo.m</code>, just type <code>foo</code> from within the Octave command prompt to execute it. You have to make sure that the script is in your current working directory or in Octave's load path. Type {{manual|pwd}} to get the current working directory or type {{manual|path}} to see which paths belong to Octave's load path. The current working directory is referred to as "." in the output of {{manual|path}}.


If the script name has characters that are not valid for an Octave identifier, or if you do not want to use addpath to add the script's location to the current path, you can use the <code>run</code> function instead:
If the script name has characters that are not valid for an Octave identifier, or if you do not want to use {{manual|addpath}} to add the script's location to the current path, you can use the {{manual|run}} function instead:


  octave> run("Script Name With Spaces.m")
<syntaxhighlight lang="octave">
  octave> run("/opt/local/foo.m")
run ("Script Name With Spaces.m")
run ("/opt/local/foo.m")
</syntaxhighlight>


An alternative is to run the script from outside Octave by calling Octave from your operating system shell. Unlike calling the script from inside Octave, this also allows you to pass arguments from the shell into the script, which the script can access using the <code>argv</code> command:
An alternative is to run the script from outside Octave by calling Octave from your operating system shell. Unlike calling the script from inside Octave, this also allows you to pass arguments from the shell into the script, which the script can access using the {{manual|argv}} command:


   $ octave the-script.m arg1 arg2
   $ octave the-script.m arg1 arg2
Line 282: Line 298:
If you call the script from the shell and it's plotting, please note [[#When I try plotting from a script, why am I not seeing anything?|how to plot when running a script from the shell]].
If you call the script from the shell and it's plotting, please note [[#When I try plotting from a script, why am I not seeing anything?|how to plot when running a script from the shell]].


==How do I erase a figure?==  
==How do I close a figure?==  


closeplot();
To close the current figure type {{manual|close}} in the Octave command prompt.
closefig(number)


==How do I set the number of displayed decimals?==
==How do I set the number of displayed decimals?==


    octave:1> format long
You can control the number of displayed decimals using the {{manual|format}} command:
    octave:2> pi
    pi = 3.14159265358979
    octave:3> format short
    octave:4> pi
    pi = 3.1416


==How do I call an octave function from C++?==
<syntaxhighlight lang="octave">
>> format long
>> pi
pi = 3.14159265358979
>> format short
>> pi
pi = 3.1416
</syntaxhighlight>


* Here is an untested code snippet for calling rand([9000,1]), modified from a post by Herber Farnsworth? to help-octave on 2003-05-01:
==How do I call an Octave function from C++?==


#include <octave/oct.h>
Please read the manual https://www.gnu.org/software/octave/doc/interpreter/Calling-Octave-Functions-from-Oct_002dFiles.html.
...
ColumnVector NumRands(2);
NumRands(0) = 9000;
NumRands(1) = 1;
octave_value_list f_arg, f_ret;
f_arg(0) = octave_value(NumRands);
f_ret = feval("rand",f_arg,1);
Matrix unis(f_ret(0).matrix_value());


==How do I change color/line definition in gnuplot postscript?==
==How do I change color/line definition in gnuplot postscript?==
Line 350: Line 359:
==How do I tell if a file exists?==
==How do I tell if a file exists?==


Look at functions like exist, file_in_path.. and the other functions that their descriptions point to.
One can use the function {{manual|exist}} to tell if a regular file, say <code>foo.txt</code> exist in Octave's load path, or the current directory:
 
<syntaxhighlight lang="octave">
>> exist ("foo.txt", "file")  # 2, if file exists, 0 otherwise
ans = 2
</syntaxhighlight>


==How do I create a plot without a window popping up (plot to a file directly)?==
==How do I create a plot without a window popping up (plot to a file directly)?==


'''This only works with gnuplot as graphics_toolkit, NOT with fltk. See [https://savannah.gnu.org/bugs/?33180 Bug#33180]'''
<syntaxhighlight lang="octave">
figure (1, "visible", "off");
plot (sin (1:100));
print -deps "/tmp/sin.eps"
</syntaxhighlight>


  figure(1, "visible", "off");
One can set that behavior as default:
  plot(sin(1:100));
  print -deps "/tmp/sin.eps"


One can set that behaviour as default:
<syntaxhighlight lang="octave">
set (0, "defaultfigurevisible", "off");
</syntaxhighlight>


  set(0, 'defaultfigurevisible', 'off');
==How do I increase Octave's precision?==


==How do I make Octave use more precision?==
Octave's default numerical type is [https://en.wikipedia.org/wiki/IEEE_754 IEEE 754] binary64 , a.k.a. "double" or "hardware floats".  This type has a precision of 53 bits or about 16 decimal digits. It is supported by each modern computer hardware, so it is really '''fast'''.  This type is assumed throughout for Octave's calculations.  If more precision was required, one can obtain a "few bits more" by using integer types, e.g. {{manual|uint64}}, but in general one cannot expect more precision from any '''fast''' numerical software.  Just to visualize "how big" those numerical limits are, consider the following table:


Octave's default numerical type is IEEE 754 doubles, a.k.a. hardware floats. This type has 52 bits of precision or about 16 decimal digits. It's implemented in your computer's hardware, in your CPU, so it's '''fast'''. This type is assumed throughout for Octave's calculations.
{| class="wikitable"
|+ Limits of some of Octave's data types obtained by {{manual|intmax}} and {{manual|flintmax}}.
|-
| <code>intmax ("uint64")</code>
| style="text-align: right;" | <code>18,446,744,073,709,551,615</code>
| <code>2^64-1</code>
|-
| <code>intmax ("int64")</code>
| style="text-align: right;" | <code>9,223,372,036,854,775,807</code>
| <code>2^63-1</code>
|-
| <code>flintmax ("double")</code>
| style="text-align: right;" | <code>9,007,199,254,740,992</code>
| <code>2^53</code>
|-
| <code>flintmax ("single")</code>
| style="text-align: right;" | <code>16,777,216</code>
| <code>2^24</code>
|}


You can use a few other built-in types. The int64 type will have 63 bits of precision. One bit is used for the sign, but if you don't want to lose that bit, uint64 can be used instead. These types, however, cannot represent numbers as large as the default double type, and can only represent integers. Furthermore, there is no way to represent integer literals, so if you do
When working with other types than "double" in Octave, one has to make sure, that the first operand is converted to the desired type:


<syntaxhighlight lang="Octave">uint64(18446744073709551610);</syntaxhighlight>
<syntaxhighlight lang="Octave">
 
>> uint64 (2^53 + 1)
the literal "18446744073709551610" first gets converted to a double precision type, so <code>uint64</code>'s additional precision is lost. Instead, initialize the <code>uint64</code> with smaller numbers and perform a computation to get the larger number you want. E.g.,
ans = 9007199254740992
 
>> uint64 (2^53) + 1
<syntaxhighlight lang="Octave">uint64(999999999999999) * 10000</syntaxhighlight>
ans = 9007199254740993
</syntaxhighlight>


would produce value 9999999999999990000, which is close to the maximum possible value for the uint64 type, but can't be at the moment input directly, doing uint64(9999999999999990000), due to the mentioned error of rounding.
Notice the difference, in the first line the addition within the brackets is performed using double precision, therefore the result gets "truncated" to the maximum possible value without a warning.  The third line uses throughout uint64 precision.


Alternatively, one may use arbitrary precision arithmetic, which has as much precision as is practical to hold in your computer's memory. The ''symbolic'' package has a vpa() function for arbitrary precision arithmetic. Note that arbitrary precision arithmetic must be implemented '''in software''' which makes it much slower than hardware floats.
Consider carefully if your problem really needs more precision.  Often if you're running out of precision the problem lies fundamentally in your methods being [https://en.wikipedia.org/wiki/Numerical_stability numerically unstable], thus more precision will not help you here.


Consider carefully if your problem really needs more precision. Often if you're running out of precision the problem lies fundamentally in your methods being [http://en.wikipedia.org/wiki/Numerical_stability numerically unstable], so more precision will not help you here. If you absolutely must use arbitrary-precision arithmetic, you're at present better off using a CAS instead of Octave. An example of such a CAS is [http://sagemath.org Sage].
If you absolutely must have more precision, you're at present better off using a [https://en.wikipedia.org/wiki/Computer_algebra_system CAS] instead of Octave.  However, CAS or symbolic computations must be implemented '''in software''' which makes it much slower than hardware floats. An example of such a CAS is [http://www.sagemath.org/ Sage] or have a look at Octave's [[Symbolic package]].


==How do I run a Matlab P-file in Octave?==
==How do I run a Matlab P-file in Octave?==


You can't. Matlab P-files (files with a .p file extension), also known as P-code, are [https://en.wikipedia.org/wiki/Obfuscation_%28software%29 obfuscated] files than cannot be run outside of Matlab itself. The original source Matlab m-files that were used to generate the P-files should be used in Octave instead.
You can't. Matlab P-files (files with a <code>.p</code> file extension), also known as P-code, are [https://en.wikipedia.org/wiki/Obfuscation_%28software%29 obfuscated] files than cannot be run outside of Matlab itself. The original source Matlab m-files that were used to generate these P-files should be used in Octave instead.


There are no plans to support running P-files produced by Matlab in Octave.
There are no plans to support running P-files produced by Matlab in Octave.
Line 390: Line 427:
==How does Octave solve linear systems?==
==How does Octave solve linear systems?==


In addition to consulting Octave's source for the precise details, you can read the Octave manual for a complete high-level description of the algorithm that Octave uses to decide how to solve a particular linear system, e.g. how the backslash operator {{Codeline|A\x}} will be interpreted.  Sections [http://www.octave.org/doc/interpreter/Techniques-Used-for-Linear-Algebra.html Techniques Used for Linear Algebra] and [http://www.octave.org/doc/interpreter/Sparse-Linear-Algebra.html Linear Algebra on Sparse Matrices] from the manual describe this procedure.
In addition to consulting Octave's source for the precise details, you can read the Octave manual for a complete high-level description of the algorithm that Octave uses to decide how to solve a particular linear system, e.g. how the backslash operator <code>A \ x</code> will be interpreted.  Sections [http://www.octave.org/doc/interpreter/Techniques-Used-for-Linear-Algebra.html Techniques Used for Linear Algebra] and [http://www.octave.org/doc/interpreter/Sparse-Linear-Algebra.html Linear Algebra on Sparse Matrices] from the manual describe this procedure.


==How do I do X?==
==How do I do X?==


You are probably looking for the function ''lookfor''. This function searches the help text of all functions for a specific string and returns a list of functions. Note that by default it will only search the first line of the help text (check ''help lookfor'' at the octave prompt for more). The following example helps to find the function to calculate correlation coefficient in a matrix:
You are probably looking for the function {{manual|lookfor}}. This function searches the help text of all functions for a specific string and returns a list of functions. Note that by default it will only search the first line of the help text (check <code>help lookfor</code> at the octave prompt for more). The following example helps to find the function to calculate correlation coefficient in a matrix:


   octave> lookfor correlation
   >> lookfor correlation
   corr2              Returns the correlation coefficient between I and J.
   corr                Compute matrix of correlation coefficients.
  cor                Compute correlation.
   corrcoef            Compute a matrix of correlation coefficients.
   corrcoef            Compute correlation.
   spearman            Compute Spearman's rank correlation coefficient RHO.
   spearman            Compute Spearman's rank correlation coefficient RHO for each of the variables sp
  autocor            Return the autocorrelations from lag 0 to H of vector X.


Also, there's a high chance that the function name has a suggestive name, and so you can try auto-completion to get some hints. For the previous example, typing ''corr'' at the octave promp followed by pressing [Tab] twice would suggest the following:
Also, there's a high chance that the function name has a suggestive name, and so you can try auto-completion to get some hints. For the previous example, typing <code>corr</code> at the octave prompt followed by pressing the {{key press|Tab}}-Key twice would suggest the following:


   octave> corr
   >> corr
   corr2     corrcoef
   corr     corrcoef


=Common problems=
=Common problems=


==I am running a script that should produce output during execution but I don't see anything until it has finished==
==I do not see any output of my script until it has finished?==


By default Octave is set to pass its screen output through a pager (usually the default pager is "less") which allows
By default Octave is set to pass its screen output through a [https://en.wikipedia.org/wiki/Terminal_pager pager] (usually the default pager is "less") which allows things such as navigating through the output with arrow keys or searching for text or regular expressions within the output. The pager only displays the output after it's finished receiving it, so when it is active you'll not be able to see anything until your script has terminated. To change this behavior temporarily or permanently you may want to use one of the options described [http://www.octave.org/doc/interpreter/Paging-Screen-Output.html in the manual].
things such as navigating through the output with arrow keys or searching for text or regular expressions within the output.
The pager only displays the output after it's finished receiving it, so when it is active you'll not be able to see anything until your script has terminated. To change this behavior temporarily or permanently you may want to use one of the options described [http://www.octave.org/doc/interpreter/Paging-Screen-Output.html here].


==When I try plotting from a script, why am I not seeing anything?==
==When I try plotting from a script, why am I not seeing anything?==


If you are running an Octave script that includes a plotting command, the script and Octave may terminate immediately. So the plot window does show up, but immediately closes when Octave finishes execution. Alternatively, if using fltk, the plot window needs a readline loop to show up (the time when Octave is sitting around doing nothing waiting for interactive input).
If you are running an Octave script that includes a plotting command, the script and Octave may terminate immediately. So the plot window does show up, but immediately closes when Octave finishes execution. Alternatively, if using fltk, the plot window needs a readline loop to show up (the time when Octave is sitting around doing nothing waiting for interactive input).
 
A common solution is to put a {{Codeline|pause}} command at the end of your script.
 
==How do I get sound input or output in Windows?==
Sound input from a sound card and output to a sound card is fully supported in Octave 4.0.0 and newer in all operating systems. Older versions of Octave had very limited audio support that was essentially Linux-specific. If you have problems with the audio I/O functions using Octave 4.0 or a newer version, please report them on the [http://bugs.octave.org bug tracker].
 
==I cannot install a package. Octave complains about a missing mkoctfile.==
 
You should normally use your distribution's packages. For Debian and Fedora, Octave package '''foo''' will be a deb or rpm called '''octave-foo''', and you should install that instead using apt or yum.


If you really need to build Octave packages from source to install them, you'll need mkoctfile. Most distributions split Octave into several packages. The script mkoctfile is then part of a separate package:
A common solution is to put a {{manual|pause}} command at the end of your script.


* Debian/Ubuntu: {{Codeline|octave-headers}} or {{Codeline|liboctave-dev}}
==How do I get sound input or output in Windows?==


* Fedora: {{Codeline|octave-devel}}
Sound input from a sound card and output to a sound card is fully supported since Octave 4.0.0 for all platforms.  If you have problems with the [http://www.octave.org/doc/interpreter/Audio-Processing.html audio I/O functions] using Octave 4.0.0 or a newer version, please report them on the [http://bugs.octave.org bug tracker].


==I'm having problem X using the latest Octave version==
==I have problem X using the latest Octave version==


Please be more specific. What is the latest version, according to you? If you mean the latest released version, be aware that you may still have an older version due to whatever distribution method you're using. There may be a newer version available that you're not aware of due to the distribution method you're using to get Octave, and in most cases, there is a way to get a newer version via your distribution method (see other wiki pages for [[Octave_for_GNU/Linux|GNU/Linux]], [[Octave_for_MacOS_X|Mac OSX]], and [[Octave_for_Windows|Windows]]).
Please be more specific about what you mean by "latest version"?


If you mean the latest Mercurial revision, please specify which one that is. "Latest tip" is not informative, because from the time you wrote "latest tip" to the time someone reads that message, "latest tip" might have changed meaning. Also, you might be standing on a different commit than what "hg tip" says. The tip may be on a different branch, or you might have updated to a different revision different from what "hg tip" says.
* The latest stable version is {{Release}}. Be aware that you may still have an older version due to whatever distribution method you are using. To get a newer stable version for your system see for example [[Octave for GNU/Linux|GNU/Linux]], [[Octave for macOS|macOS]], or [[Octave for Microsoft Windows|Windows]]).


Instead, report the output of "hg summary" or "hg id". Also please use hashes instead or in addition to revision numbers. Revision numbers are just a convenience and only make sense in your local repo, and might not coincide with what someone sees on their own repo. Hashes are globally unique across all repos.
* If you refer to the latest Mercurial revision, please specify the [https://www.mercurial-scm.org/wiki/ChangeSetID changeset ID] not the revision number, e.g. the output of <code>hg summary</code> or <code>hg id</code>. Changeset IDs are globally unique across all repos.


If your problem truly persists with the latest version, as indicated [http://www.gnu.org/software/octave/download.html here], then by all means report a bug or ask for help, but don't be surprised if volunteers are less inclined to help you with a problem that only exists in an older version of Octave.
If your problem truly persists with the "latest version", then please [http://bugs.octave.org/ report a bug] or ask for help at[https://lists.gnu.org/mailman/listinfo/help-octave help@octave.org].  Otherwise, don't be surprised if volunteers are less inclined to help you with a problem that only exists in an older version of Octave and is already fixed in a newer version.


==Why is Octave's floating-point computation wrong?==
==Why is Octave's floating-point computation wrong?==


Floating point arithmetic is an approximation '''in binary''' to arithmetic on real or complex numbers. Just like you cannot represent 1/3 exactly in decimal arithmetic (0.333333 is only a rough approximation to 1/3), you cannot represent some fractions like <math>1/10</math> exactly in base 2. In binary, the representation to one tenth is <math>0.0\overline{0011}_b</math> where the bar indicates that it repeats infinitely (like how <math>1/6 = 0.1\overline{6}_d</math> in decimal). Because this infinite repetition cannot be represented exactly with a finite number of digits, rounding errors occur for values that appear to be exact in decimal but are in fact approximations in binary, such as for example how 0.3 - 0.2 - 0.1 is not equal to zero.
Floating-point arithmetic is an approximation '''in binary''' to arithmetic on real or complex numbers. Just like you cannot represent 1/3 exactly in decimal arithmetic (0.333333... is only a rough approximation to 1/3), you cannot represent some fractions like <math>1/10</math> exactly in base 2. In binary, the representation to one tenth is <math>0.0\overline{0011}_b</math> where the bar indicates that it repeats infinitely (like how <math>1/6 = 0.1\overline{6}_d</math> in decimal). Because this infinite repetition cannot be represented exactly with a finite number of digits, rounding errors occur for values that appear to be exact in decimal but are in fact approximations in binary, such as for example how 0.3 - 0.2 - 0.1 is not equal to zero.
 
In addition, some advanced operations are computed by approximation and are not guaranteed to be accurate, see [https://en.wikipedia.org/wiki/Rounding#Table-maker.27s_dilemma Table-maker's dilemma]. Their results are system-dependent.
 
This isn't an Octave bug. It happens with any program that uses [http://en.wikipedia.org/wiki/IEEE_754 IEEE 754 floating point arithmetic]. To be fair, IEEE 754 also specifies decimal floating point arithmetic, which has never seen wide adoption. The reason why Octave and other programs use IEEE 754 binary floats is that they are ''fast'', because they are implemented in hardware or system libraries. Unless you are using very exotic hardware, Octave will use your computer's processor for basic floating point arithmetic.


Like death and taxes, rounding errors are a fact of life. You cannot avoid them. You can only move a rounding error from one part of a computation to another, or you can use more precision and delay the rounding error. One way to delay the rounding error is to use arbitrary precision arithmetic, which is inevitably slower as it has to be implemented in software instead of hardware. You may use the vpa function from the symbolic package for this purpose.
In addition, some advanced operations are computed by approximation and are not guaranteed to be accurate, see [https://en.wikipedia.org/wiki/Rounding#Table-maker.27s_dilemma Table-maker's dilemma]. Their results are system-dependent.


Another approach to the problem is interval arithmetic with the [[Interval package]]. Then, the exact result would always be enclosed by two binary floats. Again, this is slower since only the most basic interval arithmetic operations can be performed in hardware.
This isn't an Octave bug.  It happens with any program that uses [https://en.wikipedia.org/wiki/IEEE_754 IEEE 754 floating-point arithmetic]. To be fair, IEEE 754 also specifies decimal floating-point arithmetic, which has never seen wide adoption.  The reason why Octave and other programs using IEEE 754 binary floating-point numbers is that they are ''fast'', because they are implemented in hardware or system libraries. Unless you are using very exotic hardware, Octave will use your computer's processor for basic floating-point arithmetic.


To learn more about floating point arithmetic, consult [http://en.wikipedia.org/wiki/Floating_point_arithmetic its Wikipedia article] or the classical reference [http://floating-point-gui.de/ What Every Computer Scientist Should Know About Floating Point Arithmetic].
Another approach to deal with rounding errors is interval arithmetic with the [[Interval package]] or symbolic computatons with the [[Symbolic package]].  These approaches are likely to be slower, since not all operations can be performed on Hardware like pure floatin-point arithmetic.


==I have installed a package but still get a "foo undefined" error?==
To learn more about floating-point arithmetic, consult the [https://en.wikipedia.org/wiki/Floating-point_arithmetic Wikipedia article] or the classical reference by David Goldberg [http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html What Every Computer Scientist Should Know About Floating-Point Arithmetic].
 
You have probably forgotten to load the package. Use {{Codeline|pkg load package-name}} to load it. Most packages are no longer loaded automatically to avoid surprises. See reasoning on related FAQ [[FAQ#How_do_I_install_all_Octave_packages.3F|how do I install all Octave packages]]. If you want a specific package to be loaded by default at startup, consider adding the {{Codeline|pkg load}} command on your {{path|[[.octaverc]]}} file.


==Missing lines when printing under Windows with OpenGL toolkit and Intel integrated GPU==
==Missing lines when printing under Windows with OpenGL toolkit and Intel integrated GPU==
Line 467: Line 485:
Some windows users with integrated Intel GPUs have reported missing lines when printing with an OpenGL toolkit like FLTK or Qt. {{bug|42534}}
Some windows users with integrated Intel GPUs have reported missing lines when printing with an OpenGL toolkit like FLTK or Qt. {{bug|42534}}


Users with this kind of problem should try to install/update their Intel OpenGL drivers for Windows or consider installing Mesa drivers from http://qt-project.org/wiki/Cross-compiling-Mesa-for-Windows
Users with this kind of problem should try to install/update their Intel OpenGL drivers for Windows or consider installing Mesa drivers from http://qt-project.org/wiki/Cross-compiling-Mesa-for-Windows .


See also https://www.opengl.org/wiki/FAQ#Why_is_my_GL_version_only_1.4_or_lower.3F
See also https://www.opengl.org/wiki/FAQ#Why_is_my_GL_version_only_1.4_or_lower.3F .


==Plot hangs and makes the GUI unresponsive==
==Plot hangs and makes the GUI unresponsive==


If the Qt graphics toolkit is used and "plot" is used for the first time, the fontconfig scanner searches the font directory to build a font cache. This can take up to 3min on slow CPUs. See {{bug|45458}}
If the Qt graphics toolkit is used and "plot" is used for the first time, the fontconfig scanner searches the font directory to build a font cache. This can take up to 3min on slow CPUs. See {{bug|45458}}
==Error message about invalid call to script or invalid use of script in index expression==
If Octave shows an error message about {{Codeline|invalid call to script .../close.m}} or {{Codeline|invalid use of of script .../close.m in index expression}}, it means that you have created a script called close.m that is overriding the built-in Octave function {{Codeline|close}}. Octave functions and scripts share the samem global namespace. It is best to avoid creating your own scripts or functions that have the same name as an Octave function.


=Differences between Octave and Matlab=
=Differences between Octave and Matlab=
Line 489: Line 511:
</blockquote>
</blockquote>


which is not quite the same thing. There are still a number of differences between Octave and Matlab, however in general differences between the two are considered as bugs. Octave might consider that the bug is in Matlab and do nothing about it, but generally functionality is almost identical. If you find an important functional difference between Octave behavior and Matlab, then you should send a description of this difference (with code illustrating the difference, if possible) to http://bugs.octave.org.
which is not quite the same thing. There are still a number of differences between Octave and Matlab, however in general differences between the two are considered as bugs. Octave might consider that the bug is in Matlab and do nothing about it, but generally functionality is almost identical. If you find an important functional difference between Octave behavior and Matlab, then you should send a description of this difference (with code illustrating the difference, if possible) to http://bugs.octave.org.


Furthermore, Octave adds a few syntactical extensions to Matlab that might cause some issues when exchanging files between Matlab and Octave users.
Furthermore, Octave adds a few syntactical extensions to Matlab that might cause some issues when exchanging files between Matlab and Octave users.
Line 499: Line 521:
==Nested Functions==
==Nested Functions==


Octave has limited support for nested functions. That is
Octave has limited support for nested functions since version 3.8.0. That is


          function y = foo (x)
<syntaxhighlight lang="Matlab">
            y = bar(x)
function y = foo (x)
            function y = bar (x)
  y = bar(x)
              y = ...;
  function y = bar (x)
            end
    y = ...;
          end
  end
end
</syntaxhighlight>


is equivalent to
is equivalent to


          function y = foo (x)
<syntaxhighlight lang="Octave">
            y = bar(x)
function y = foo (x)
          end
  y = bar(x)
          function y = bar (x)
endfunction
            y = ...;
 
          end
function y = bar (x)
  y = ...;
endfunction
</syntaxhighlight>


The main difference with Matlab is a matter of scope. While nested functions have access to the parent function's scope in Matlab, no such thing is available in Octave, due to how Octave essentially “un-nests” nested functions.
The main difference with Matlab is a matter of scope. While nested functions have access to the parent function's scope in Matlab, no such thing is available in Octave, due to how Octave essentially “un-nests” nested functions.


The authors of Octave consider the nested function scoping rules of Matlab to be more problems than they are worth as they introduce difficult to find bugs as inadvertently modifying a variable in a nested function that is also used in the parent is particularly easy for those not attentive to detail.
The authors of Octave consider the nested function scoping rules of Matlab to be more problems than they are worth as they introduce difficult to find bugs as inadvertently modifying a variable in a nested function that is also used in the parent is particularly easy for those not attentive to detail.
Line 525: Line 552:
There are a few core Matlab syntaxes that are not accepted by Octave, these being
There are a few core Matlab syntaxes that are not accepted by Octave, these being


* Some limitations on the use of function handles. The major difference is related to nested function scoping rules (as above) and their use with function handles.
* Some limitations on the use of function handles. The major difference is related to nested function scoping rules (as above) and their use with function handles.


* Some limitations of variable argument lists on the LHS of an expression, though the most common types are accepted.
* Some limitations of variable argument lists on the LHS of an expression, though the most common types are accepted.


* Matlab classdef object oriented programming is not yet supported, though work is underway in a branch of the development tree.
* Matlab classdef object oriented programming is only partially supported, see [[classdef]] for details.


==Differences in core functions==
==Differences in core functions==


A large number of the Matlab core functions (ie those that are in the core and not a toolbox) are implemented, and certainly all of the commonly used ones. There are a few functions that aren't implemented, usually to do with specific missing Octave functionality (GUI, DLL, Java, ActiveX, DDE, web, and serial functions). Some of the core functions have limitations that aren't in the Matlab version. For example the sprandn function can not force a particular condition number for the matrix like Matlab can. Another example is that testing and the runtests function work differently in Matlab and Octave.
A large number of the Matlab core functions (i.e. those that are in the core and not a toolbox) are implemented, and certainly all of the commonly used ones. There are a few functions that aren't implemented, usually to do with specific missing Octave functionality (GUI, DLL, Java, ActiveX, DDE, web, and serial functions). Some of the core functions have limitations that aren't in the Matlab version. For example the {{manual|sprandn}} function can not force a particular condition number for the matrix like Matlab can. Another example is that testing and the runtests function work differently in Matlab and Octave.


==Just-In-Time compiler==
==Just-In-Time compiler==


Matlab includes a "Just-In-Time" compiler. This compiler allows the acceleration of for-loops in Matlab to almost native performance with certain restrictions. The JIT must know the return type of all functions called in the loops and so you can't include user functions in the loop of JIT optimized loops. Octave doesn't have a JIT and so to some might seem slower than Matlab. For this reason you must vectorize your code as much as possible. The MathWorks themselves have a good document discussing vectorization at http://www.mathworks.com/support/tech-notes/1100/1109.html.
Matlab includes a "Just-In-Time" compiler. This compiler allows the acceleration of for-loops in Matlab to almost native performance with certain restrictions. The JIT must know the return type of all functions called in the loops and so you can't include user functions in the loop of JIT optimized loops. Octave has a [[JIT|not fully functional JIT compiler]]. For this reason you must [[Performance#Vectorization|vectorize your code]] as much as possible. The MathWorks themselves have a good document discussing vectorization at http://www.mathworks.com/support/tech-notes/1100/1109.html.


==Compiler==
==Compiler==


On a related point, there is no Octave compiler, and so you can't convert your Octave code into a binary for additional speed or distribution. There have been several aborted attempts at creating an Octave compiler. Should the JIT compiler above ever be implemented, an Octave compiler should be more feasible.
On a related point, there is no Octave compiler, and so you can't convert your Octave code into a binary for additional speed or distribution.


==Graphic handles==
==Graphic handles==


Up to Octave 2.9.9 there was no support for graphic handles in Octave itself. In the 3.2.N versions of Octave and beyond, the support for graphics handles is converging towards full compatibility. The patch function is currently limited to 2-D patches, due to an underlying limitation in gnuplot, but the experimental OpenGL backend is starting to see an implementation of 3-D patches.
The support for graphics handles is converging towards full compatibility. If you notice any incompatibilities, please [http://bugs.octave.org report a bug].


==GUI functions==
==GUI functions==


There are no Matlab compatible GUI functions yetThis might be an issue if you intend to exchange Octave code with Matlab users. There are a number of bindings from Octave to {{Forge|tcl-octave|Tcl/Tk}}, [http://octaviz.sourceforge.net/index.php? VTK] and {{Forge|zenity}} for example, that can be used for a GUI, but these are not Matlab compatible. Work on a Matlab compatible GUI is in an alpha stage in the QtHandles project, which may form part of a future release of Octave.
The support for [http://www.octave.org/doc/interpreter/GUI-Development.html Matlab compatible GUI functions] was added in Octave version 3.6.0 and is converging towards full compatibilityIf you notice any incompatibilities, please [http://bugs.octave.org report a bug].


==Simulink==
==Simulink==


Octave itself includes no Simulink support. Typically the simulink models lag research and are less flexible, so shouldn't really be used in a research environment. However, some Matlab users that try to use Octave complain about this lack.
Octave itself includes no Simulink support. Typically the simulink models lag research and are less flexible, so shouldn't really be used in a research environment. However, some Matlab users that try to use Octave complain about this lack.


==MEX-Files==
==MEX-Files==


Octave includes an API to the Matlab MEX interface. However, as MEX is an API to the internals of Matlab and the internals of Octave differ from Matlab, there is necessarily a manipulation of the data to convert from a MEX interface to the Octave equivalent. This is notable for all complex matrices, where Matlab stores complex arrays as real and imaginary parts, whereas Octave respects the C99/C++ standards of co-locating the real/imag parts in memory. Also due to the way Matlab allows access to the arrays passed through a pointer, the MEX interface might require copies of arrays (even non complex ones).
Octave includes an [http://www.octave.org/doc/interpreter/Mex_002dFiles.html API to the Matlab MEX interface]. However, as MEX is an API to the internals of Matlab and the internals of Octave differ from Matlab, there is necessarily a manipulation of the data to convert from a MEX interface to the Octave equivalent. This is notable for all complex matrices, where Matlab stores complex arrays as real and imaginary parts, whereas Octave respects the C99/C++ standards of co-locating the real/imag parts in memory. Also due to the way Matlab allows access to the arrays passed through a pointer, the MEX interface might require copies of arrays (even non complex ones).


==Block comments==
==Block comments==


Block comments denoted by {{Codeline|#{}} and {{Codeline|#&#125;}markers (or {{Codeline|%{}} and {{Codeline|%&#125;}}) are supported by Octave with some limitations. The major limitation is that block comments are not supported within [] or {}.
Block comments denoted by <code>#{</code> and <code>#}</code> markers (or <code>%{</code> and <code>%}</code>) are supported by Octave with some limitations. The major limitation is that block comments are not supported within [] or {}.


==Mat-File format==
==Mat-File format==


There are some differences in the mat v5 file format accepted by Octave. Matlab recently introduced the "-V7.3" save option which is an HDF5 format which is particularly useful for 64-bit platforms where the standard Matlab format can not correctly save variables. Octave accepts HDF5 files, but is not yet compatible with the "-v7.3" versions produced by Matlab.
There are some differences in the mat v5 file format accepted by Octave. Matlab recently introduced the "-V7.3" save option which is an HDF5 format which is particularly useful for 64-bit platforms where the standard Matlab format can not correctly save variables. Octave accepts HDF5 files, but is not yet compatible with the "-v7.3" versions produced by Matlab.


Although Octave can load inline function handles saved by Matlab, it can not yet save them.
Although Octave can load inline function handles saved by Matlab, it can not yet save them.
Line 573: Line 600:
==Profiler==
==Profiler==


Thanks to Daniel Kraft's 2011 Google Summer of Code project, Octave has a profiler since version 3.6.0. However, at the moment it only produces text output and has its own makeshift interface for hierarchical profiling.
Thanks to Daniel Kraft's 2011 Google Summer of Code project, [http://www.octave.org/doc/interpreter/Profiling.html Octave has a profiler] since version 3.6.0.


==Toolboxes==
==Toolboxes==


Octave is a community project and so the toolboxes that exist are donated by those interested in them through [[Octave Forge]]. These might be lacking in certain functionality relative to the Matlab toolboxes, and might not exactly duplicate the Matlab functionality or interface.
Octave is a community project and so the toolboxes that exist are donated by those interested in them through [[Octave Forge]]. These might be lacking in certain functionality relative to the Matlab toolboxes, and might not exactly duplicate the Matlab functionality or interface.


==Short-circuit {{Codeline|&}} and {{Codeline|&#124;}} operators==
==Short-circuit <code>&</code> and <code>|</code> operators==


The {{Codeline|&}} and {{Codeline|&#124;}} operators in Matlab short-circuit when included in a condition (e.g. an {{Codeline|if}} or {{Codeline|while}} statement) and not otherwise. In Octave only the {{Codeline|&&}} and {{Codeline|&#124;&#124;}} short circuit. Note that this means that
The <code>&</code> and <code>|</code> operators in Matlab short-circuit when included in a condition (e.g. an {{Codeline|if}} or {{Codeline|while}} statement) and not otherwise. In Octave only the <code>&&</code> and <code>||</code> short circuit. Note that this means that


            if (a | b)
<syntaxhighlight lang="Octave">
              ...
if (a | b)
            end
  ...
end
</syntaxhighlight>


and
and


            t = a | b;
<syntaxhighlight lang="Octave">
            if t
t = a | b;
              ...
if (t)
            end
  ...
end
</syntaxhighlight>
 
have different semantics in Matlab.  This is really a Matlab bug, but there is too much code out there that relies on this behavior to change it.  Prefer the <code>&&</code> and <code>||</code> operators in {{Codeline|if}} statements if possible.


have different semantics in Matlab. This is really a Matlab bug, but there is too much code out there that relies on this behavior to change it. Prefer the {{Codeline|&#124;&#124;}} and {{Codeline|&&}} operators in {{Codeline|if}} statements if possible. If you need to use code written for Matlab that depends on this buggy behavior, you can enable it since Octave 3.4.0 with the following command:
Note that the difference with Matlab is also significant when either argument is a function with side effects or if the first argument is a scalar and the second argument is an empty matrix. For example, note the difference between


            do_braindead_shortcircuit_evaluation(1)
<syntaxhighlight lang="Octave">
t = 1 | [];          ## results in [], so...
if (t) 1, end        ## in if ([]), this is false.
</syntaxhighlight>


Note that the difference with Matlab is also significant when either argument is a function with side effects or if the first argument is a scalar and the second argument is an empty matrix. For example, note the difference between
and


            t = 1 | [];          ## results in [], so...
<syntaxhighlight lang="Octave">
            if (t) 1, end       ## in if ([]), this is false.
if (1 | []) 1, end   ## short circuits so condition is true.
</syntaxhighlight>


and
In the latter case, Octave displays since version 4.0.0 a warning:


            if (1 | []) 1, end   ## short circuits so condition is true.
   warning: Matlab-style short-circuit operation performed for operator |


Another case that is documented in the Matlab manuals is that
Another case that is documented in the Matlab manuals is that


            t = [1, 1] | [1, 2, 3];          ## error
<syntaxhighlight lang="Matlab">
            if ([1, 1] | [1, 2, 3]) 1, end  ## OK
t = [1, 1] | [1, 2, 3];          ## error
if ([1, 1] | [1, 2, 3]) 1, end  ## OK
</syntaxhighlight>


Also Matlab requires the operands of {{Codeline|&&}} and {{Codeline|&#124;&#124;}} to be scalar values but Octave does not (it just applies the rule that for an operand to be considered true, every element of the object must be nonzero or logically true).
Also Matlab requires the operands of <code>&&</code> and <code>||</code> to be scalar values but Octave does not (it just applies the rule that for an operand to be considered true, every element of the object must be nonzero or logically true).


Finally, note the inconsistence of thinking of the condition of an {{Codeline|if}} statement as being equivalent to {{Codeline|all(X(:))}} when {{Codeline|X}} is a matrix. This is true for all cases EXCEPT empty matrices:
Finally, note the inconsistence of thinking of the condition of an {{Codeline|if}} statement as being equivalent to {{Codeline|all(X(:))}} when {{Codeline|X}} is a matrix. This is true for all cases EXCEPT empty matrices:


            if ([0, 1]) == if (all ([0, 1]))  ==>  i.e., condition is false.
<syntaxhighlight lang="Matlab">
            if ([1, 1]) == if (all ([1, 1]))  ==>  i.e., condition is true.
if ([0, 1]) == if (all ([0, 1]))  ==>  i.e., condition is false.
if ([1, 1]) == if (all ([1, 1]))  ==>  i.e., condition is true.
</syntaxhighlight>


However,
However,


            if ([])
<syntaxhighlight lang="Matlab">
if ([])
</syntaxhighlight>


is not the same as
is not the same as


            if (all ([]))
<syntaxhighlight lang="Matlab">
if (all ([]))
</syntaxhighlight>


because, despite the name, the {{Codeline|all}} is really returning true if none of the elements of the matrix are zero, and since there are no elements, well, none of them are zero. This is an example of [http://en.wikipedia.org/wiki/Vacuous_truth vacuous truth]. But, somewhere along the line, someone decided that {{Codeline|if ([])}} should be false. Mathworks probably thought it just looks wrong to have {{Codeline|[]}} be true in this context even if you can use logical gymnastics to convince yourself that "all" the elements of an empty matrix are nonzero. Octave however duplicates this behavior for {{Codeline|if}} statements containing empty matrices.
because, despite the name, the {{manual|all}} is really returning true if none of the elements of the matrix are zero, and since there are no elements, well, none of them are zero. This is an example of [https://en.wikipedia.org/wiki/Vacuous_truth vacuous truth]. But, somewhere along the line, someone decided that {{Codeline|if ([])}} should be false. The Mathworks probably thought it just looks wrong to have {{Codeline|[]}} be true in this context even if you can use logical gymnastics to convince yourself that "all" the elements of an empty matrix are nonzero. Octave however duplicates this behavior for {{Codeline|if}} statements containing empty matrices.


==Solvers for singular, under- and over-determined matrices==
==Solvers for singular, under- and over-determined matrices==


Matlab's solvers as used by the operators mldivide (\) and mrdivide (/), use a different approach than Octave's in the case of singular, under-, or over-determined matrices. In the case of a singular matrix, Matlab returns the result given by the LU decomposition, even though the underlying solver has flagged the result as erroneous. Octave has made the choice of falling back to a minimum norm solution of matrices that have been flagged as singular which arguably is a better result for these cases.
Matlab's solvers as used by the operators {{manual|mldivide}} <code>\</code> and {{manual|mrdivide}} <code>/</code>, use a different approach than Octave's in the case of singular, under-, or over-determined matrices. In the case of a singular matrix, Matlab returns the result given by the LU decomposition, even though the underlying solver has flagged the result as erroneous. Octave has made the choice of falling back to a minimum norm solution of matrices that have been flagged as singular which arguably is a better result for these cases.


In the case of under- or over-determined matrices, Octave continues to use a minimum norm solution, whereas Matlab uses an approach that is equivalent to
In the case of under- or over-determined matrices, Octave continues to use a minimum norm solution, whereas Matlab uses an approach that is equivalent to


          function x = mldivide (A, b)
<syntaxhighlight lang="Octave">
            m = rows(A);
function x = mldivide (A, b)
            [Q, R, E] = qr(A);
  m = rows (A);
            x = [A \ b, E(:, 1:m) * (R(:, 1:m) \ (Q' * b))]
  [Q, R, E] = qr (A);
          end
  x = [A \ b, E(:, 1:m) * (R(:, 1:m) \ (Q' * b))]
end
</syntaxhighlight>


While this approach is certainly faster and uses less memory than Octave's minimum norm approach, this approach seems to be inferior in other ways.
While this approach is certainly faster and uses less memory than Octave's minimum norm approach, this approach seems to be inferior in other ways.


A numerical question arises: how big can the null space component become, relative to the minimum-norm solution? Can it be nicely bounded, or can it be arbitrarily big? Consider this example:
A numerical question arises: how big can the null space component become, relative to the minimum-norm solution? Can it be nicely bounded, or can it be arbitrarily big? Consider this example:


          m = 10;
<syntaxhighlight lang="Octave">
          n = 10000;
m = 10;
          A = ones(m, n) + 1e-6 * randn(m,n);
n = 10000;
          b = ones(m, 1) + 1e-6 * randn(m,1);
A = ones (m, n) + 1e-6 * randn (m, n);
          norm(A \ b)
b = ones (m, 1) + 1e-6 * randn (m, 1);
norm (A \ b)
</syntaxhighlight>


while Octave's minimum-norm values are around 3e-2, Matlab's results are 50-times larger. For another issue, try this code:
while Octave's minimum-norm values are about 3e-2, Matlab's results are 50-times larger. For another issue, try this code:


          m = 5;
<syntaxhighlight lang="Octave">
          n = 100;
m = 5;
          j = floor(m * rand(1, n)) + 1;
n = 100;
          b = ones(m, 1);
j = floor (m * rand (1, n)) + 1;
          A = zeros(m, n);
b = ones (m, 1);
          A(sub2ind(size(A),j,1:n)) = 1;
A = zeros (m, n);
          x = A \ b;
A(sub2ind(size(A),j,1:n)) = 1;
          [dummy,p] = sort(rand(1,n));
x = A \ b;
          y = A(:,p)\b;
[~,p] = sort (rand (1, n));
          norm(x(p)-y)
y = A(:,p) \ b;
norm (x(p) - y)
</syntaxhighlight>


It shows that unlike in Octave, mldivide in Matlab is not invariant with respect to column permutations. If there are multiple columns of the same norm, permuting columns of the matrix gets you different result than permuting the solution vector. This will surprise many users.
It shows that unlike in Octave, {{manual|mldivide}} in Matlab is not invariant with respect to column permutations. If there are multiple columns of the same norm, permuting columns of the matrix gets you different result than permuting the solution vector. This will surprise many users.


Since the mldivide (\) and mrdivide (/) operators are often part of a more complex expression, where there is no room to react to warnings or flags, it should prefer intelligence (robustness) to speed, and so the Octave developers are firmly of the opinion that Octave's approach for singular, under- and over-determined matrices is a better choice than Matlab's.
Since the {{manual|mldivide}} <code>\</code> and {{manual|mrdivide}} <code>/</code> operators are often part of a more complex expression, where there is no room to react to warnings or flags, it should prefer intelligence (robustness) to speed, and so the Octave developers are firmly of the opinion that Octave's approach for singular, under- and over-determined matrices is a better choice than Matlab's.


==Octave extensions==
==Octave extensions==
Line 678: Line 729:
Octave has a lisp-like {{Codeline|unwind_protect}} block that allows blocks of code that terminate in an error to ensure that the variables that are touched are restored. You can do something similar with try/catch combined with {{Codeline|rethrow (lasterror ())}} in Matlab, however rethrow and lasterror are only available in Octave 2.9.10 and later. MATLAB 2008a also introduced {{Codeline|OnCleanUp}} that is similar to {{Codeline|unwind_protect}}, except that the object created by this function has to be explicitly cleared in order for the cleanup code to run.
Octave has a lisp-like {{Codeline|unwind_protect}} block that allows blocks of code that terminate in an error to ensure that the variables that are touched are restored. You can do something similar with try/catch combined with {{Codeline|rethrow (lasterror ())}} in Matlab, however rethrow and lasterror are only available in Octave 2.9.10 and later. MATLAB 2008a also introduced {{Codeline|OnCleanUp}} that is similar to {{Codeline|unwind_protect}}, except that the object created by this function has to be explicitly cleared in order for the cleanup code to run.


Note that using try/catch combined with {{Codeline|rethrow (lasterror ())}} can not guarantee that global variables will be correctly reset, as it won't catch user interrupts with Ctrl-C. For example
Note that using try/catch combined with {{Codeline|rethrow (lasterror ())}} cannot guarantee that global variables will be correctly reset, as it won't catch user interrupts with Ctrl-C. For example


          global a
<syntaxhighlight lang="Matlab">
          a = 1;
global a
          try
a = 1;
            _a = a;
try
            a = 2
  _a = a;
            while true
  a = 2
            end
  while true
          catch
  end
            fprintf ('caught interrupt\n');
catch
            a = _a;
  fprintf ('caught interrupt\n');
            rethrow (lasterror());
  a = _a;
          end
  rethrow (lasterror());
end
</syntaxhighlight>


compared to
compared to


          global a
<syntaxhighlight lang="Octave">
          a = 1;
global a
          unwind_protect
a = 1;
            _a = a;
unwind_protect
            a = 2
  _a = a;
            while true
  a = 2
            end
  while true
          unwind_protect_cleanup
  end
            fprintf ('caught interrupt\n');
unwind_protect_cleanup
            a = _a;
  fprintf ('caught interrupt\n');
          end
  a = _a;
end
</syntaxhighlight>


Typing Ctrl-C in the first case returns the user directly to the prompt, and the variable ''a'' is not reset to the saved value. In the second case the variable ''a'' is reset correctly. Therefore Matlab gives no safe way of temporarily changing global variables.
Typing Ctrl-C in the first case returns the user directly to the prompt, and the variable <code>a</code> is not reset to the saved value. In the second case the variable <code>a</code> is reset correctly. Therefore Matlab gives no safe way of temporarily changing global variables.


Indexing can be applied to all objects in Octave and not just variables. Therefore {{Codeline|sin(x)(1:10)}} for example is perfectly valid in Octave but not Matlab. To do the same in Matlab you must do {{Codeline|y &#61; sin(x); y &#61; y([1:10]);}}
Indexing can be applied to all objects in Octave and not just variables. Therefore {{Codeline|sin(x)(1:10)}} for example is perfectly valid in Octave but not Matlab. To do the same in Matlab you must do {{Codeline|y &#61; sin(x); y &#61; y([1:10]);}}
Line 722: Line 777:
Functions can be defined by entering code on the command line, a feature not supported by Matlab. For example, you may type:
Functions can be defined by entering code on the command line, a feature not supported by Matlab. For example, you may type:


    octave:1> function s = hello_string (to_who)
<syntaxhighlight lang="Octave">
    > ## Say hello
>> function s = hello_string (to_who)
    > if nargin<1, to_who = "World"; end
> ## Say hello
    > s = ["Hello ",\
> if nargin<1, to_who = "World"; end
    >      to_who];
> s = ["Hello ",\
    > endfunction
>      to_who];
    octave:2> hello_string ("Moon")
> endfunction
    ans = Hello Moon
>> hello_string ("Moon")
ans = Hello Moon
</syntaxhighlight>


As a natural extension of this, functions can also be defined in script files (m-files whose first non-comment line isn't {{Codeline|function out &#61; foo (...)}})
As a natural extension of this, functions can also be defined in script files (m-files whose first non-comment line isn't {{Codeline|function out &#61; foo (...)}})
Line 741: Line 798:
===Strings delimited by double quotes "===
===Strings delimited by double quotes "===


The double quote, {{Codeline|"}}, may be used to delimit strings, in addition to the single quote {{Codeline|'}}. See the previous example. Also, double-quoted strings include backslash interpretation (like C++, C, and Perl) while single quoted are uninterpreted (like Matlab and Perl).
In 2016, Matlab introduced String Arrays, that are initialized by using double quoted strings, and are not implemented in Octave yet. In Octave double-quoted strings include backslash interpretation (like C++, C, and Perl) while single quoted are uninterpreted (like Matlab and Perl).


===Line continuation by backslash===
===Line continuation by backslash===


Lines can be continued with a backslash, {{Codeline|\}}, in addition to three points {{Codeline|...}}. See the previous example.
Lines can be continued with a backslash, {{Codeline|\}}, in addition to three points {{Codeline|...}} as in Matlab.


===Informative block closing===
===Informative block closing===
Line 755: Line 812:
Indexing other things than variables is possible, as in:
Indexing other things than variables is possible, as in:


    octave:1> [3 1 4 1 5 9](3)
<syntaxhighlight lang="Octave">
    ans = 4
>> [3 1 4 1 5 9](3)
    octave:2> cos([0 pi pi/4 7])(3)
ans = 4
    ans = 0.70711
>> cos([0 pi pi/4 7])(3)
ans = 0.70711
</syntaxhighlight>


In Matlab, it is for example necessary to assign the intermediate result {{Codeline|cos([0 pi pi/4 7])}} to a variable before it can be indexed again.
In Matlab, it is for example necessary to assign the intermediate result {{Codeline|cos([0 pi pi/4 7])}} to a variable before it can be indexed again.
Line 766: Line 825:
The exclamation mark {{Codeline|!}} (aka “Bang!”) is a negation operator, just like the tilde {{Codeline|~}}:
The exclamation mark {{Codeline|!}} (aka “Bang!”) is a negation operator, just like the tilde {{Codeline|~}}:


    octave:1> if ! strcmp (program_name, "octave"),
<syntaxhighlight lang="Octave">
    >  "It's an error"
>> if ! strcmp (program_name, "octave"),
    > else
>  "It's an error"
    >  "It works!"
> else
    > end
>  "It works!"
    ans = It works!
> end
ans = It works!
</syntaxhighlight>
 
Note however that Matlab uses the {{Codeline|!}} operator for shell escapes, for which Octave requires using the system command.
Note however that Matlab uses the {{Codeline|!}} operator for shell escapes, for which Octave requires using the system command.


Line 788: Line 850:
In addition to try-catch blocks, Octave supports an alternative form of exception handling modeled after the unwind-protect form of Lisp. The general form of an unwind_protect block looks like this:
In addition to try-catch blocks, Octave supports an alternative form of exception handling modeled after the unwind-protect form of Lisp. The general form of an unwind_protect block looks like this:


    unwind_protect
<syntaxhighlight lang="Octave">
      body
unwind_protect
    unwind_protect_cleanup
  body
      cleanup
unwind_protect_cleanup
    end_unwind_protect
  cleanup
end_unwind_protect
</syntaxhighlight>


Where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are guaranteed to be executed regardless of how control exits body.
Where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are guaranteed to be executed regardless of how control exits body.
Line 798: Line 862:
The unwind_protect statement is often used to reliably restore the values of global variables that need to be temporarily changed.
The unwind_protect statement is often used to reliably restore the values of global variables that need to be temporarily changed.


Matlab can be made to do something similar with their {{Codeline|onCleanup}} function that was introduced in 2008a. Octave also has {{Codeline|onCleanup}} since version 3.4.0.
Matlab can be made to do something similar with their {{manaul|onCleanup}} function that was introduced in 2008a. Octave also has {{manual|onCleanup}} since version 3.4.0.


===Built-in ODE and DAE solvers===
===Built-in ODE and DAE solvers===
Line 806: Line 870:
===Do-Until loop structure===
===Do-Until loop structure===


Similar to the do-while loop in C and C++, Octave allows a do-until loop which does not exist in Matlab
Similar to the do-while loop in C and C++, Octave allows a do-until loop which does not exist in Matlab:


  x = 0
<syntaxhighlight lang="Octave">
  do
x = 0
    x += 1;
do
  until (x == 10)
  x += 1;
until (x == 10)
</syntaxhighlight>


===Broadcasting===
===Broadcasting===


Borrowed from [http://stackoverflow.com/q/26948776/3565696 other languages], [http://www.gnu.org/software/octave/doc/v4.0.1/Broadcasting.html octave broadcasting] allows easy and readable vectorization.
Borrowed from [http://stackoverflow.com/q/26948776/3565696 other languages], [http://www.octave.org/doc/interpreter/Broadcasting.html octave broadcasting] allows easy and readable vectorization.


  f = (1:0.1:2);
<syntaxhighlight lang="Octave">
  # put angular frequencies on the first dimension to prepare broadcasting
f = (1:0.1:2);
  omega = 2 * pi * f(:);
# put angular frequencies on the first dimension to prepare broadcasting
  # time is already on the second dimension (row vector)
omega = 2 * pi * f(:);
  t = 0:0.02:2;
# time is already on the second dimension (row vector)
  # the resulting s will be a 2-dimensional array
t = 0:0.02:2;
  s = sin(omega .* t);
# the resulting s will be a 2-dimensional array
  # which can be displayed as
s = sin(omega .* t);
  pcolor(t, f, s)
# which can be displayed as
  xlabel("t (s)")
pcolor(t, f, s)
  ylabel("f (Hz)")
xlabel("t (s)")
ylabel("f (Hz)")
</syntaxhighlight>


Note: [https://www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-operations.html Automatic expansion of dimensions] was added to MATLAB R2016b.
Note: [https://www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-operations.html Automatic expansion of dimensions] was added to MATLAB R2016b.
Line 838: Line 906:


Octave allows to add self-tests to user defined functions. Tests are put after function definition in specially commented block.
Octave allows to add self-tests to user defined functions. Tests are put after function definition in specially commented block.
 
 
  function mult = a(val)
<syntaxhighlight lang="Octave">
          mult = val.*2;
function mult = a(val)
  endfunction
  mult = val.*2;
  %!test
endfunction
  %! assert (a(3), 6);
%!test
%! assert (a(3), 6);
</syntaxhighlight>


Such a function can be tested for valid outputs by following code:
Such a function can be tested for valid outputs by following code:


   octave:1> test a
   >> test a
   PASSES 1 out of 1 test
   PASSES 1 out of 1 test


===Demonstration Functions===
===Demonstration Functions===


Example code block can be part of function file in a similar manner as test functions. For example to run demo for function multinom of package specfun, use:
Example code block can be part of function file in a similar manner as test functions. For example to run {{manual|demo}} for function multinom of package specfun, use:


   demo multinom
   demo multinom


===Powerfull assert===
===Powerful assert===


Function assert have extended input possibilities.
Function assert have extended input possibilities.

Navigation menu