You are on page 1of 44

7.

 Octave script files
A powerful feature of Octave is that it can execute (at one go) a series of Octave
commands that you may have already saved in a file. You can use your favourite
editor (such as Emacs) to create such a file, then later execute all its commands in
Octave. Such files are called 'script files'. They are also known as 'm­files' because
they have the extension '.m' following the tradition of Matlab users. We recommend
that you follow in that same tradition by appending your m­files with the same
extension. There are added advantages to doing this.
One reason why the m­file feature is so powerful is that it transforms Octave into a
programming language: you can code a complicated program (which is essentially a
series of executable commands) into an m­file and later run the program by simply
entering the name of the m­file without the '.m' extension in the Octave command
prompt. If you did not name your m­file with the '.m' extension then you can run your
file only with the following command: 
source "filename" 
for example, the following command,
octave:1> source "experiment1" 
executes the contents of the file called experiment1.
For this reason Octave provides the usual programming constructs such as, if­
statements, for­loops, while­loops and function definitions. You can use these
constructs together with any of the other Octave commands you know.
As an example, here are the contents of an m­file which plots a bifurcation plot for a
difference equation:
clear all;
verbose = 1;
mu1 = 4;
mu0 = 1;
N = 2000;
x0 = 0.8;

clearplot;
axis([1 4 0 1])

gset xzeroaxis ls 0 lt 1 lw 1
gset yzeroaxis ls 0 lt 1
gset xlabel "Growth Rate, r";
gset ylabel "Equilibrium Point, x*";

for i = (1 : N + 1)
mu = mu0 + (i - 1) * (mu1 - mu0) / N;
clear x;
x(1) = x0;
j = 2;
notconverged = 1;
while (notconverged)
x(j) = mu * x(j - 1) * (1 - x(j - 1));
j++;
for k = (1 : j - 2)
if (abs(x(k) - x(j-1)) < 0.0001)
kstar = k;
notconverged = 0;
break;
endif
endfor
endwhile
clear muon;
clear xstar;
muon = 1;
xstar = 0;
for n = (kstar : j - 2)
muon = [muon ; mu];
xstar = [xstar ; x(n)];
endfor
M = [muon xstar];
command = \
sprintf("gset title \"BIFURCATION PLOT FOR THE LOGISTIC MAP (1 < r
< %f). Period = %d\"" \
,mu,j-1-kstar);
eval(command);
hold on
gplot M title "" with dots 0
if (verbose)
if ((j - 1 - kstar) == 3)
ans = input("Ready? Enter 1 to continue to the end ...\n");
if (ans == 1) verbose = 0; endif
endif
endif
endfor
gset title "BIFURCATION PLOT FOR THE LOGISTIC MAP (1 < r < 4)"
replot
hold off;

7.1. Flow Control
Until now, Octave executed everything that we typed into either the Octave interpreter
(or programme) or into our script files. It is also posibble—and very useful—to write
a scripts that executes only some of its code or that performs some operation
repeatedly. For example, the following simple example calculates the absolute value
of a number:
x = -3;
if x <= 0
x = -x;
endif
disp(['Absolute value: ', num2str(x)]);

Copy and paste this code into Octave and try it out for different values of x. This piece
of code changes the sign of x if and only if it is less than 0.
Loops
Loops are used to repeat a block of code for a known or unknown number of times,
depending on the type of loop. We will demonstrate the use of loops using some
simple examples as well as fractals1.

The for statement

We use for loops when we know
● how many times a loop is to be executed and 
● for which values of a particular variable it will be executed. 
As an example, let's say that we want to calculate an integer power of a real number
the long way. We can write
an = a × a × ... × a   (n−1 multiplications).
To programme this in Octave, we have to be able to multiply a number n−1 times for
any value of n. The code below will do just that.

Warning: file(code/power.m): failed to open stream: No such file or


directory in /var/www/resources/tutorials/octave/oct_flow.php on line
40

Warning: implode(): Bad arguments. in /


var/www/resources/tutorials/octave/oct_flow.php on line 40

You can download the code as power.m.
You can try this for different values of a and n and test the result (stored in the
product variable) by calculating the power with a^n. This code produces a lot of
output but it will give you an idea of how the loop is executed.
Each integer value in the range 2...n is assigned to the variable i in order and the code
inside the for loop executed for that value.
Note that in Octave, the expression 2:n generates a vector of integer values ranging
from 2 to n. In general, a for loop can range over the values in any vector. The general
structure of a for loop is
for variable = vector
...
endfor

For example, the following code will sum the values in a vector

Warning: file(code/add.m): failed to open stream: No such file or


directory in /var/www/resources/tutorials/octave/oct_flow.php on line
62
Warning: implode(): Bad arguments. in /
var/www/resources/tutorials/octave/oct_flow.php on line 62

You can download the code as add.m.

Exercises

1. Write a script that sums the first N integers. You can check your result with the
formula ½N(N+1). 
2. Write a script that does the same thing as the linspace() function. It should start
at some value xstart, stop at xstop and create a vector that contains N values
evenly spaced from xstart to xstop. You might find the zeros() function useful
to create an empty vector to start with. 

Example: The Serpinski triangle

The Serpinksi triangle is a fractal that can be generated with a very simple
algorithm.
1. Start on a vertex of an equilateral triangle. 
2. Select a vertex at random. 
3. Move to the point halfway between where you are now and the selected vertex.
4. Repeat from step 2. 
Plotting the points that you visit by following this procedure, will generate the picture
on the right.
You can download the code that generates this fractal as serpinski.m. Note that this
code uses one very simple for loop to generate the fractal:—
for i = 2:N
...
endfor

The while statement

The while loop also executes a block of code more than once but stops based on a
logical condition. For example
x = 1.0;
while x < 1000
x = x*2;
disp(x);
endwhile

will multiply x by 2 until its value exceeds 1000. Here, x < 1000 is the condition of
the loop. As long as the condition holds (is true), the loop will continue executing. As
soon as it is false, the loop terminates and the first instruction after the loop is
executed.
The general form of a while loop is
while condition
...
endwhile

Exercise

1. Write a script that calculates the smallest positive integer, n, such that an ≥ b
for some real numbers a and b. (Meaning, find the smallest power of a that is
at least b.) Using the log() function is considered cheating. 

Example: The Mandelbrot fractal

The Mandelbrot set is another fractal and is generated by checking how
long it takes a complex number to become large. For each complex
number, c,
1. Start with z0 = 0. 
2. Let zi = zi−12 + c  for all i = 1, 2, ... 
3. Find the first i such that |zi| > 2. 

We record all of these i values and assign a colour to each of them. This is used to
generate an image such as the one on the right.
You can download the code that generates this fractal as mandelbrot.m. Note that
there is a while loop (inside some for loops) that tests whether the complex number z
has modulus less than 2:—
while (count < maxcount) & (abs(z) < 2)
...
endwhile

The first condition in the while loop checks that we do not perform too many
iterations. For some values of c the iteration will go on forever if we let it.

The do...until statement

These loops are very similar to while loops in that they keep executing based on
whether a given condition is true or false. There are however some important
difference between while and do...until loops.
● while loops have their conditions at the beginning of the loop; 
do...until loops have theirs at the end. 
● while loops repeat as long as the condition is true; 
do...until loops continue as long as theirs is false. 
● while will execute 0 or more times (because the condition is at the beginning); 
do...until loops will execute 1 or more times (since the condition is at the end).
The general form of a do...until loop is
do
...
until condition
Exercises

1. Write a script that calculates the greatest common divisor (GCD)
of two positive integers. You can do this using Euclid's algorithm. 
2. Write a script that generates random number pairs (a, b) that are distributed
uniformly over 
1. the interval [­1, 1] × [­1, 1] 
2. the disc {(x, y) | x2 + y2 ≤ 1} 
When plotting the number pairs for Exercise 2.2, you should get a picture like the one
to the right.

The break and continue statements

Sometimes it is necessary to stop a loop somewhere in the middle of its execution or
to move on to the next value in a for loop without executing the rest of the loop code
for the current value. This is where the break and continue statements are useful.
The following code demonstrates how the break statement works.

Warning: file(code/test_break.m): failed to open stream: No such


file or directory in /var/www/resources/tutorials/octave/oct_flow.php
on line 204

Warning: implode(): Bad arguments. in /


var/www/resources/tutorials/octave/oct_flow.php on line 204

You can download the code as test_break.m.
Without the break statement, the loop would keep executing forever since the
condition of the while loop is always true. The break allows you to jump past the end
of the loop (to the statement after the endwhile).
The break statement can be used in any loop: for, while or do...until.
The continue statement also jumps from the inside of a loop but returns to the
beginning of the loop rather than going to the end. In a
● for loop, the next value inside the vector will be assigned to the for variable (if
there are any left) and the loop restarted with that value; 
● while loop, the condition at the beginning of the loop will be retested and the
loop continued if it is still true; 
● do...until loop, the condition at the end of the loop will be tested and the loop
continued from the beginning if it is still false. 
As an example, the following code will fill the lower triangular part of a square matrix
with 1s and the rest with 0s.

Warning: file(code/test_continue.m): failed to open stream: No such


file or directory in /var/www/resources/tutorials/octave/oct_flow.php
on line 234
Warning: implode(): Bad arguments. in /
var/www/resources/tutorials/octave/oct_flow.php on line 234

You can download the code as test_continue.m.
Note that the inner for skips (continues) over the code that assigns a 1 to an entry of A
whenever the column index is greater than the row index.

Conditional statements
Conditional statements are executed at most once, depending on whether a condition
is true or false.

The if statement

The general form of the if statement is
if condition1
...
elseif condition2
...
else
...
endif

If condition1 evaluates to true, the statements in the block immediately following the
if are executed. If condition1 is false, the next condition (condition2 in the elseif) is
checked and its statements executed if it is true. You can have as many elseif
statements as you like. The final set of statements, after the else, is executed if all of
the conditions evaluate to false. Note that the elseif and else parts of the if statement
are optional.
The following are all valid if statements:
% Take the log of the absolute value of x
if x > 0
y = log(x);
elseif x < 0
y = log(-x);
else
disp("Cannot take the log of zero.");
endif

x = input("Enter a value: ");


if x > 0
disp("The number is positive");
endif

if x < 0
disp("The number is negative");
endif
if x == 0
disp("The number is zero");
endif

Example: The fractal fern

The image to the right can be generated with the following algorithm:
1. Let x1 and y1 be random values between 0 and 1. 
2. Choose one of the linear transformations below to calculate (xi+1, yi+1) from
(xi, yi): 
1. xi+1 = 0 
yi+1 = 0.16yi 
2. xi+1 = 0.20xi − 0.26yi 
yi+1 = 0.23xi + 0.22yi + 1.6 
3. xi+1 = −0.15xi + 0.28yi 
yi+1 = 0.26xi + 0.24yi + 0.44 
4. xi+1 = 0.85xi + 0.04yi 
yi+1 = −0.04xi + 0.85yi + 1.6 
The first transformation is chosen if probability 0.01, the second and third with
probability 0.07 each and the fourth with probability 0.85. 
3. Calculate these values for i up to at least 10,000. 
You can download the code that generates this fractal as fracfern.m (this is disabled
for now).

1. "A fractal [...] is a geometric object which can be divided into parts, each of which
is similar to the original object. Fractals are said to possess infinite detail [...]" (from
Wikipedia) [Back]

8. Reading and writing data
There are a number of ways to save and load data or results from Octave
computations. The first, and easiest, is using the save and load commands. These
commands write and read Octave variables to and from a file. They can be used if you
want to save your results, quit Octave and return later. The command
save filename

will store all variables in a file called filename. You can also use
save filename x y z

to store only the variables x, y and z. The restore variables from a file use
load filename
Note that this will replace the values of any variables that have the same names as the
ones being loaded from the file.

Exporting data

When using save and load, Octave stores data in an internal format, i.e. one that is not
necessarily easy to read by us (or other computer programmes, for that matter).
Saving data in some custom format is known as exporting.
The printf, sprintf and fprintf functions can be used to write strings and variables to
the screen, a string and an file, repsectively. We will discuss formatting of output
using printf but it applies to sprintf and fprintf as well.
The printf outputs the values of a scalar, vector or matrix based on a formatting string.
This string tells Octave how to interpret the values inside the variable. For now, take
note of the following formatting parameters:
%i integer values
%f real values in decimal format
%e real values in exponent format
%g real numbers in either decimal or exponent
See the example below for a demonstration of the formatting parameters:
octave:5> A = [1, 1.3, 0.000001, 1000000, 0.001]
A =

1.0000e+00 1.3000e+00 1.0000e-06 1.0000e+06 1.0000e-03

octave:6> printf("%i ", A); printf("\n");


1 1 0 1000000 0

octave:7> printf("%f ", A); printf("\n");


1.000000 1.300000 0.000001 1000000.000000 0.001000

octave:8> printf("%e ", A); printf("\n");


1.000000e+00 1.300000e+00 1.000000e-06 1.000000e+06 1.000000e-03

octave:9> printf("%g ", A); printf("\n");


1 1.3 1e-06 1e+06 0.001

See help ­i printf for more information.

Importing data

Just like the printf function can be used to write data, the scanf function can be used to
read it. The function also requires a formatting string that tells Octave wat type of data
to expect. It then returns the value read from the console (scanf), string (sscanf) or file
(fscanf) in a variable. A typical command to read one integer from a file looks like
this:
x = fscanf(fid, "%i");
Here, fid is the file id from which the data is read. See the section below for more
details on file ids and help ­i scanf for more information on reading data.

Opening and closing files

In order to read data from or write it to a file, we need to open the file first. This is
done with the fopen function. With this function, we specify the filename to open and
the mode in which to open it. The possible modes are
 r  reading
 w  writing
 a  appending
After opening a file for reading, we can use the fscanf function to read values from it.
The first value will be read from the beginning of the file, the second from the
position just after tha and so on. When opening a file for writing, the file is created if
it doesn't exist or cleared if it does. Then fprintf function is then used to write data to
the file. Opening a file for appending does not erase any existing data, but adds new
data to the end of the file using the fprintf function.
The save data written to a file, we have to close it using the fclose function.
The following example will create a file called testdata and write some data to it.
octave:1> A = rand(4); # Create a 4x4 random matrix
octave:2> fid = fopen("testdata", "w"); # Open and clear the file
octave:3> fprintf(fid, "%f ", A); # Write the values of A to
the file
octave:4> fclose(fid); # Close the file

Octave:Getting started
From AIMSWiki

Table of contents [showhide] 
1 Starting Octave
2 Entering commands
3 Plotting
3.1 Exercise
3.2 More on commands
3.3 Example
4 Exercises
4.1 Warning
5 Challenge
6 Script files
The aim of this tutorial is to give you a quick introduction to basic Octave and to
show that you know a lot of it already. If you should ever get stuck or need more
information on an Octave function or command, type 
help command

at the Octave prompt. command is the name of the Octave command or function on
which to find help. Be warned though that the descriptions can sometimes be a bit
technical and filled with jargon. 
[edit]

Starting Octave 
Type octave in a terminal window to get started. You should see the following. 
GNU Octave, version 2.1.69 (i386-pc-linux-gnu).
Copyright (C) 2005 John W. Eaton.
This is free software; see the source code for copying conditions.
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTIBILITY or
FITNESS FOR A PARTICULAR PURPOSE. For details, type `warranty'.

Additional information about Octave is available at


http://www.octave.org.

Please contribute if you find this software useful.


For more information, visit http://www.octave.org/help-wanted.html

Report bugs to <bug@octave.org> (but first, please read


http://www.octave.org/bugs.html to learn how to write a helpful
report).

octave:1>

[edit]

Entering commands 
The last line above is known as the Octave prompt and, much like the prompt in
Linux, this is where you type Octave commands. To do simple arithmetic, use +
(addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation).
Many mathematical functions are also available and have obvious names, e.g. sin,
cos, log, abs (absolute value). 
Here are some examples showing the input typed at the prompt and the output
returned by Octave. 

2 + 3

octave:1> 2 + 3 octave:2> log(100)/log(10) octave:3> floor((1+tan(1.2)) / 1.2) octave


ans = 5 ans = 2 ans = 2 ans =
Some things to note: 
● Octave requires parentheses around the input of a function (so, log(10) is
fine, but (log 10) is not). 
● Any spacing before and after arithmetic operators is optional, but allowed. 
● Not all Octave functions have obvious names (e.g. sqrt above). Don't panic
for now. You will get to know them as we go along. 
[edit]

Plotting 
You are going to plot the following pictures using Octave: 

Figure 1 Figure 2

Figure 3 Figure 4
Figure 1 contains a plot of x vs sin x and is generated with the following commands.
(It's a bit boring but illustrates the basic functionality.) 
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);

The command that actually generates the plot is, of course, plot(x, y). Before
executing this commmand, we need to set up the variables, x and y. The plot
function simply takes takes two vectors of equal length as input, interprets the values
in the first as x­coordinates and the second as y­coordinates and draws a line
connecting these coordinates. 
The first command above, x = linspace(0, 2*pi), uses the linspace
function to make a vector of linearly spaced values. The first value in the vector is 0,
the final value is 2π and the vector contains 100 values. This vector is assigned to the
variable named x. 
The second command computes the sin of each value in the vector variable, x, and
stores the resulting vector in the variable y. 
(As an aside: the name of a variable can be any sequence of letters, digits and
underscores that does not start with a digit. There is no maximum length for variable
names, and the case of alphabetical characters is important, i.e. a and A are two
different variable names.) 
[edit]

Exercise 

Plot the function   for  . (This is Figure 2). 


[edit]

More on commands 
The following commands and functions are useful for setting up variables for plotting
2D graphs. 
● linspace creates a vector of evenly (linearly) spaced values. 
Usage: linspace(start, stop, length). The length parameter is
optional and specifies the number of values in the returned vector. If you leave out
this parameter, the vector will contain 100 elements with start as the first value and
stop as the last. 
● plot plots a 2­dimensional graph. 
Usage: plot(x, y) where x and y are vectors of equal length. 
● figure creates a new plotting window. 
This is useful for when you want to plot multiple graphs in separate windows rather
than replacing your previous graph or plotting on the same axes. 
● hold on and hold off sets whether you want successive plots to be
drawn together on the same axes or to replace the previous plot. 
[edit]

Example 
We are going to plot Figures 3 and 4. Figure 3 contains the 3 trigonometric functions 
● cos2x, 
● sin4x, and 
● 2sinx 
on one set of axes. Figure 4 contains the sum of these 3 functions. 
Firstly, we use linspace to set up a vector of x­values. 
octave:1> x = linspace(0, 2*pi);

Then, we compute the y­values of the 3 functions. 
octave:2> a = cos(2*x);
octave:3> b = sin(4*x);
octave:4> c = 2*sin(x);

The following plots the first graph. 
octave:5> figure;
octave:6> plot(x, a);
octave:7> hold on;
octave:8> plot(x, b);
octave:9> plot(x, c);

We use line 5 (figure) to tell Octave that we want to plot on a new set of axes. It is
good practice to use figure before plotting any new graph. This prevents your
accidentally replacing a previous plot with the new one. 
Note that on line 7, hold on is used to tell Octave that we don't want to replace the
first plot (from line 6) with subsequent ones. Octave will plot everything after hold
on on the same axes, until the hold off command is issued. 
Finally, we plot the second graph. 
octave:10> figure;
octave:11> hold off;
octave:12> plot(x, a+b+c);

Line 10 creates a new graph window and line 11 tells Octave that any subsequent
plots should simply replace previous ones. Line 12 generates the plot of the sum of
the 3 trigonometric functions. 
[edit]

Exercises 
● Plot the absolute value function for  . 
● Plot a circle of radius 1, centered at the origin. (This is not so easy.) 
● Plot your favourite function(s) 
[edit]

Warning 
If you try (or have tried) to plot something like x2 or  , you will run
into trouble. The following error messages are common. In the case of x^2: 
error: for A^b, A must be square
In the case of sin(x)*cos(x): 
error: operator *: nonconformant arguments (op1 is 1x100, op2 is
1x100)

This error occurs whenever you try multiply or divide two vector variables (remember
that x and y are vectors). For now, you can do one of two things. 
1. Ignore it and plot some other functions. 
2. Read the section on vectors and matrices. 
[edit]

Challenge 
Since Octave is a numerical (and not symbolic) mathematics package, it does make
numerical errors and does not handle some operations well. To confirm this, make a
plot of tan x, for x between ­π and π. What is wrong with the resulting picture? 
Your task is to generate the (much better looking) graph below using what you have
learned so far and the axis function. axis can be used to adjust which part of the
plot is actually displayed on screen. Use the command help axis to determine
how this function works. 

It might take some thinking to get the asymptote lines at   right. You can
use help plot to find out how to plot dotted lines. 
[edit]

Script files 
It is useful to be able to save Octave commands and rerun them later on. You might
want to save your work or create code that can be reused (by yourself or somebody
else). Such files are known as Octave script files. They should be saved with a .m
extension so that Octave can recognise them. (The .m extension is used because
MATLAB calls its script files M­files and Octave is based on MATLAB.) 
To run an existing script in Octave, you have to be in the same directory as the script
file and type in the name of the file without the .m in Octave. For example, if I have a
script called myscript.m in an octave directory, the following two commands
will execute the script. 
chdir('~/octave'); % This changes to the octave directory
myscript;

Note that the chdir('~/octave') command is necessary only if you are not
already inside that directory when running Octave. 
In the following section you will be shown a number of new statements that you can
use to make your Octave code much more powerful. A number of example script files
are provided and you should save these into a directory for later use. A good idea is to
create a directory called octave in your home directory and store all your Octave
files in there. 

Octave:Vectors and matrices
From AIMSWiki

Table of contents [showhide] 
1 Creating vectors and matrices
2 Operators
2.1 Element operations
3 Indexing
3.1 Ranges
4 Functions
4.1 Creating matrices
4.1.1 Other matrices
4.2 Changing matrices
5 Linear algebra

[edit]

Creating vectors and matrices 
Here is how we specify a row vector in Octave: 
octave:1> x = [1, 3, 2]
x =

1 3 2

Note that 
● the vector is enclosed in square brackets; 
● each entry is separated by a comma 
To specify a column vector, we simply replace the commas with semicolons: 
octave:2> x = [1; 3; 2]
x =

1
3
2

From this you can see that we use a comma to go to the next column of a vector (or
matrix) and a semicolon to go to the next row. So, to specify a matrix, type in the
rows (separating each entry with a comma) and use a semicolon to go to the next row. 
octave:3> A = [1, 1, 2; 3, 5, 8; 13, 21, 34]
A =

1 1 2
3 5 8
13 21 34

[edit]

Operators 
You can use the standard operators to 
● add (+), 
● subtract (-), and 
● multiply (*) 
matrices, vectors and scalars with one another. Note that the matrices need to have
matching dimensions (inner dimensions in the case of multiplication) for these
operators to work. 
● The transpose operator is the single quote: '. To continue from the example in
the previous section, 
octave:4> A'
ans =

1 3 13
1 5 21
2 8 34

(Note: this is actually the complex conjugate transpose operator, but for real matrices
this is the same as the transpose. To compute the transpose of a complex matrix, use
the dot transpose (.') operator.) 
● The power operator (^) can also be used to compute real powers of square
matrices. 
[edit]
Element operations 
When you have two matrices of the same size, you can perform element by element
operations on them. For example, the following divides each element of A by the
corresponding element in B: 
octave:1> A = [1, 6, 3; 2, 7, 4]
A =

1 6 3
2 7 4

octave:2> B = [2, 7, 2; 7, 3, 9]
B =

2 7 2
7 3 9

octave:3> A ./ B
ans =

0.50000 0.85714 1.50000


0.28571 2.33333 0.44444

Note that you use the dot divide (./) operator to perform element by element
division. There are similar operators for multiplication (.*) and exponentiation (.^). 
The dot divide operators can also be used together with scalars in the following
manner. 
C = a ./ B

returns a matrix, C where each entry is defined by 

,
i.e. a is divided by each entry in B. Similarly 
C = a .^ B

return a matrix with 

.
[edit]

Indexing 
You can work with parts of matrices and vectors by indexing into them. You use a
vector of integers to tell Octave which elements of a vector or matrix to use. For
example, we create a vector 
octave:1> x = [1.2, 5, 7.6, 3, 8]
x =
1.2000 5.0000 7.6000 3.0000 8.0000

Now, to see the second element of x, type 
octave:2> x(2)
ans = 5

You can also view a list of elements as follows. 
octave:3> x([1, 3, 4])
ans =

1.2000 7.6000 3.0000

This last command displays the 1st, 3rd and 4th elements of the vector x. 
To select rows and columns from a matrix, we use the same principle. Let's define a
matrix 
octave:4> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A =

1 2 3
4 5 6
7 8 9

and select the 1st and 3rd rows and 2nd and 3rd columns: octave:5> A([1, 3], [2, 3])
ans = 
2 3
8 9

The colon operator (:) can be used to select all rows or columns from a matrix. So, to
select all the elements from the 2nd row, type 
octave:6> A(2, :)
ans =

4 5 6

[edit]

Ranges 
We can also select a range of rows or columns from a matrix. We specify a range with
start:step:stop

The first number in the range is start, the second is start+step, the third,
start+2*step, etc. The last number is less than or equal to stop. 
You can actually type ranges at the Octave prompt to see what the results are. For
example, 
octave:3> 1:3:10
ans =
1 4 7 10

Often, you simply want the step size to be 1. In this case, you can leave out the step
parameter and type octave:4> 1:10 
ans =

1 2 3 4 5 6 7 8 9 10

As you can see, the result of a range command is simply a vector of integers. We can
now use this to index into a vector or matrix. To select the   submatrix at the
top left of A, use 
octave:4> A(1:2, 1:2)
ans =

1 2
4 5

Finally, there is a keyword called end that can be used when indexing into a matrix
or vector. It refers to the last element in the row or column. To index the last 3
elements of the vector x, use 
octave:5> x(end-2:end)
ans =

7.6000 3.0000 8.0000

[edit]

Functions 
The following functions can be used to create and manipulate matrices. 
[edit]

Creating matrices 
● tril(A) returns the lower triangular part of A. 
● triu(A) returns the upper triangular part of A. 
● eye(n) returns the   identity matrix. You can also use eye(m, n)
to return   rectangular identity matrices. 
● ones(m, n) returns an   matrix filled with 1s. 
● zeros(m, n) returns an   matrix filled with 0s. 
● rand(m, n) returns an   matrix filled with random elements drawn
uniformly from [0,1). 
● randn(m, n) returns an   matrix filled with normally distributed
random elements. 
● randperm(n) returns a row vector containing a random permutation of the
numbers  . 
● diag(x) or diag(A). For a vector, x, this returns a square matrix with the
elements of x on the diagonal and 0s everywhere else. For a matrix, A, this
returns a vector containing the diagonal elements of A. For example, 
octave:16> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A =

1 2 3
4 5 6
7 8 9

octave:17> x = diag(A)
ans =

1
5
9

octave:18> diag(x)
ans =

1 0 0
0 5 0
0 0 9

● linspace(a, b, n) returns a vector with n values, such that the first
element equals a, the last element equals b and the difference between
consecutive elements is constant. The last argument, n, is optional with default
value 100. 
● logspace(a, b, n) returns a vector with n values, such that the first
element equals 10a, the last element equals 10b and the ratio between
consecutive elements is constant. The last argument, n is optional with default
value 50. 
[edit]

Other matrices 

There are some more functions for creating special matrices. These are 
● hankel (Hankel matrix), 
● hilb (Hilbert matrix), 
● invhilb (Inverse of a Hilbert matrix), 
● sylvester_matrix (Sylvester matrix), 
● toeplitz (Toeplitz matrix), 
● vander (Vandermonde matrix). 
Use help to find out more about how to use these functions. 
[edit]

Changing matrices 
● fliplr(A) returns a copy of matrix A with the order of the columns
reversed, for example, 
octave:49> A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]
A =

1 2 3 4
5 6 7 8
9 10 11 12

octave:50> fliplr(A)
ans =

4 3 2 1
8 7 6 5
12 11 10 9

● flipud(A) returns a copy of matrix A with the order of the rows reversed,
for example, 
octave:51> flipud(A)
ans =

9 10 11 12
5 6 7 8
1 2 3 4

● rot90(A, n) returns a copy of matrix A that has been rotated by (90n)°
counterclockwise. The second argument, n, is optional with default value 1. 
octave:52> rot90(A)
ans =

4 8 12
3 7 11
2 6 10
1 5 9

● reshape(A, m, n) creates an   matrix with elements taken from


A. The number of elements in A has to be equal to mn. The elements are taken
from A in column major order, meaning that values in the first column (
) are read first, then the second column ( ),
etc. 
octave:53> reshape(A, 2, 6)
ans =

1 9 6 3 11 8
5 2 10 7 4 12
● sort(x) returns a copy of the vector x with the elements sorted in increasing
order. 
octave:54> x = rand(1, 6)
x =

0.25500 0.33525 0.26586 0.92658 0.68799 0.69682

octave:55> sort(x)
ans =

0.25500 0.26586 0.33525 0.68799 0.69682 0.92658

[edit]

Linear algebra 
For a description of more operators and functions that can be used to manipulate
vectors and matrices, find eigenvalues, etc., see the Linear algebra section. 

Octave:Plotting
From AIMSWiki

WARNING: This page is still under heavy construction

Table of contents [showhide] 
1 2D plots
1.1 Non­linear plots
1.2 Formatting
1.3 Commands related to plot
2 3D plots
3 Contour plots
4 Images
5 Saving and printing graphs
[edit]

2D plots 
plot(y)

If a single data argument is supplied, it is taken as the set of Y coordinates and the X
coordinates are taken to be the indices of the elements, starting with 1. 
plot(x, y)
● If the first argument is a vector and the second is a matrix, the the vector is
plotted versus the columns (or rows) of the matrix. (using whichever
combination matches, with columns tried first.) 
● If the first argument is a matrix and the second is a vector, the the columns (or
rows) of the matrix are plotted versus the vector. (using whichever
combination matches, with columns tried first.) 
● If both arguments are vectors, the elements of Y are plotted versus the
elements of X. 
● If both arguments are matrices, the columns of Y are plotted versus the
columns of X. In this case, both matrices must have the same number of rows
and columns and no attempt is made to transpose the arguments to make the
number of rows match. 
[edit]

Non­linear plots 
semilogx, semilogy, loglog, polar 
[edit]

Formatting 
`-'
Set lines plot style (default).

`.'
Set dots plot style.

`@'
Set points plot style.

`-@'
Set linespoints plot style.

`^'
Set impulses plot style.

`L'
Set steps plot style.

`N'
Interpreted as the plot color if N is an integer in the
range
1 to 6.

`NM'
If NM is a two digit integer and M is an integer in the
range
1 to 6, M is interpreted as the point style. This is only
valid in combination with the `@' or `-@' specifiers.

`C'
If C is one of `"r"', `"g"', `"b"', `"m"', `"c"', or `"w"',
it is interpreted as the plot color (red, green, blue,
magenta, cyan, or white).

`";title;"'
Here `"title"' is the label for the key.

`+'
`*'
`o'
`x'
Used in combination with the points or linespoints styles,
set the point style.

The color line styles have the following meanings on terminals


that
support color.

Number Gnuplot colors (lines)points style


1 red *
2 green +
3 blue o
4 magenta x
5 cyan house
6 brown there exists

The FMT argument can also be used to assign key titles. To do


so,
include the desired title between semi-colons after the
formatting
sequence described above, e.g. "+3;Key Title;" Note that the
last
semi-colon is required and will generate an error if it is left
out.

[edit]

Commands related to plot 
xlabel, ylabel, and title, replot 
[edit]

3D plots 
mesh, meshgrid, surf 
[edit]

Contour plots 
contour 
[edit]
Images 
colormap, image, imshow, hsv2rgb 
[edit]

Saving and printing graphs 
Print a graph to a printer or save it to a file 
print("-Pprinter")
print("filename", "-ddevice")

Devices: 
`ps'
`ps2'
`psc'
`psc2'
Postscript (level 1 and 2, mono and color)

`eps'
`eps2'
`epsc'
`epsc2'
Encapsulated postscript (level 1 and 2, mono and
color)

`ill'
`aifm'
Adobe Illustrator

`cdr'
`corel'
CorelDraw

`hpgl'
HP plotter language

`fig'
XFig

`dxf'
AutoCAD

`mf'
Metafont

`png'
Portable network graphics

`pbm'
PBMplus

If the device is omitted, it is inferred from the file extension, or if there is no filename
it is sent to the printer as postscript. 

Octave:Text and file output
From AIMSWiki

Table of contents [showhide] 
1 The disp function
1.1 File output
2 The printf function
2.1 Outputting to screen, string or
file
2.2 The format string
2.3 Outputting matrices

[edit]

The disp function 
The disp function displays the value of a variable (scalar, vector, matrix, string, etc.)
in the same way as simply typing the name of the variable does. For example, 
octave:1> x = [1, 2, 3]
x =

1 2 3

octave:2> disp(x)
1 2 3

The name of the variable is, however, not displayed. You can also display the result of
a computation with the and = that normally precedes it. 
octave:3> log(10)
ans = 2.3026
octave:4> disp(log(10))
2.3026

The output of disp depends on the format command. 
octave:5> format long
octave:6> disp(log(10))
2.30258509299405

The displayed value can be printed to the screen, saved in a string or saved to a file
using fdisp. 
octave:7> s = disp(log(10))
s = 2.30258509299405

Note that s is a string containing the characters shown above. 
[edit]

File output 
The fdisp function can be used to save values to a file. Before we can do this, we
have to open a file. This is done using the fopen command. 
● fopen(filename, mode) opens a file and returns an identifier for it. The
filename argument is a string and can be the name of any new or existing
file in the current directory. The mode argument is a string that specifies
whether the file is opened for 
● reading (r), 
● writing (w), or 
● appending (a). 
When a file is opened for writing, it's contents is erased and replaced with new data.
To keep the existing data in a file and add to the end thereof, use the append mode. 
octave:10> file_id = fopen('mydata.txt', 'w');

Here, file_id is simply the name of a variable that we use to tell Octave to which
file to write. 
● fdisp(fid, value) writes value to the file identified by fid. 
The output written to the file will appear exactly the same as the output from the
disp command. 
It is important to close a file after all data has been written to it. Closing the file tells
Octave to finalise any output that might still be pending and frees up the file so that it
can be opened by other users or programmes. 
● fclose(fid) closes the file identified by <code>fid. 
[edit]

The printf function 
The printf function is considerably more powerful than disp and, consequently, a
bit more complicated to use. With printf, you can define exactly what the output of
a value should look like. This includes specifying 
● the number of significant digits to display; 
● the format of the number (integer, real, scientific, etc.); 
● other output to display before or after the value. 
Since there are so many different ways to format output using printf, we will
discuss only the basics here using examples. For more complete information, type 
help -i printf

in Octave and page through the help using the spacebar key. 
[edit]

Outputting to screen, string or file 
The printf function displays its output on the screen. Use the sprintf to return
the result in a string and fprintf to write to a file. Note that the fprintf requires
one additional parameter to specify the file identifier. 
● printf(format, value, ...) 
● sprintf(format, value, ...) 
● fprintf(fid, format, value, ...) 
Note that these functions can output more than one value at the same time­­more on
this in the next section. 
[edit]

The format string 
Let's look at an example. 
octave:18> x = 10.1;
octave:19> y = 5.5;
octave:20> z = 'test';
octave:21> printf('An integer: %i. A real: %f. This is a %s.\n', x,
y, z);
An integer: 10. A real: 5.500000. This is a test.

The important part is the first argument to the printf function on line 21. It
specifies what the output of printf should look like. Essentially, the precentage
sign (%) indicates that a value should be placed at its position in the format string. In
the format string 
'An integer: %i. A real: %f. This is a %s.\n'

the %i is replaced with an integer, the %f with a real (f is for floating point) value,
and the %s with a string. The values of the integer, real and string are given as
arguments to printf after the format string. Note that x in the example above
equals 10.1, but the value displayed is 10 since we specified that printf should
display an integer. Finally, the \n at the end of the string tells Octave to move to a
new line. 
The next example demonstrates the following types: 
● integer (%i), 
● real (%f), 
● scientific notation (%e), 
● percentage symbol (%%). 
For more types, see the Octave documentation. 
octave:22> x = 10.34;
octave:23> printf("x is a real number: %f (%e in scientific
notation).\n", x, x);
x is a real number: 10.340000 (1.034000e+01 in scientific notation).
octave:24> printf("Write percentages as %i%%.\n", x);
Write percentages as 10%.

Note that 

● the %e format outputs a value in the form  , where 
and b is an integer; 
● the variable x is passed to printf twice on line 23 since we want to output it
twice (in different formats); 
● the double percentage (%%) on line 24 outputs a single percentage symbol. 
We can customize the output of values even further by specifying 
● the width of the output, and 
● the precision of the output. 
The width allows you to right align numbers and is specified between the percentage
and the format specifier. For example, 
octave:36> x = 10;
octave:37> y = pi;
octave:38> z = 'test';
octave:39> printf("%9i\n%9f\n%9s\n", x, y, z);
10
3.141593
test

Note that in the printf, each format specifier contains an integer (9). This tells
printf to use 9 columns to output the integer, real and string. 
The effect of the precision parameter depends on the type of output. It's most obvious
use is to specify the number of digits to display after the decimal point of a real
number. The precision is specified after the width and is preceded by a dot (.). 
octave:40> printf("%9.3f\n", pi);
3.142

This displays π using 9 columns and to 3 digits after the decimal point. Note that the
number is rounded. For other uses of the precision parameter (e.g. for integers and
strings), see the Octave help. 
[edit]

Outputting matrices 
When the value passed to the printf function is a matrix or vector, all of the values
in it are printed. If there is only one format specifier in the format string, it is used for
each value in the matrix. 
octave:51> A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
octave:52> printf("%i\n", A)
1
4
7
2
5
8
3
6
9

Note that the values are read from the matrix in column­major order, i.e. all the values
from the first column are displayed first, then the second column, etc. 
If there is more than one format specifier in the format string, printf cycles through
them. 
octave:57> printf("[%i, %.1f, %.2e]\n", A)
[1, 4.0, 7.00e+00]
[2, 5.0, 8.00e+00]
[3, 6.0, 9.00e+00]

The values are still read in column­major order. 

Octave:Loops and conditions
From AIMSWiki

WARNING: This page is still under heavy construction

Table of contents [showhide] 
1 The for loop
1.1 Example: The Serpinski triangle
1.2 Exercises
2 The while loop
2.1 Exercise
2.2 Example: The Mandelbrot fractal
3 The do...until statement
3.1 Exercise
3.2 Challenge
4 The break and continue statements
5 The if statement
5.1 Example: The fractal fern

Loops are used to repeat a block of code for a known or unknown number of times,
depending on the type of loop. Using loops, you will draw some nice pictures of
fractals and shapes drawn with random dots. 
[edit]

The for loop 
We use for loops to repeat a block of code for a list of known values. As an
example, we'll calculate the mean of a list of values. The mean is calculated from 

We set up a vector with some values 
octave:1> x = [1.2, 6.3, 7.8, 3.6];

and calculate the mean with 
octave:2> x_mean = 0;
octave:3> for entry = x,
octave:4> x_mean = x_mean + entry;
octave:5> endfor;
octave:6> x_mean = x_mean / length(x)

TODO: get a better example and explain the code. 

In general, we write a for loop as 
for variable = vector
...
endfor

The ... represents the block of code that is executed exactly once for each value
inside the vector. 
[edit]

Example: The Serpinski triangle 
The Serpinksi triangle is a fractal that can be generated with a very simple algorithm. 
1. Start on a vertex of an equilateral triangle. 
2. Select a vertex of the triangle at random. 
3. Move to the point halfway between where you are now and the selected vertex.
4. Repeat from step 2. 
Plotting the points that you visit by following this procedure, generates the following
picture. 
You can download the code that generates this fractal from Serpinski.m. Note that this
code uses one very simple for loop to generate the fractal: 
for i = 2:N
...
endfor

[edit]

Exercises 
1. Write a script that sums the first N integers. You can check your result with the

formula  . 
2. Write a script that does the same thing as the linspace function. It should
start at some value, xstart, stop at xstop and create a vector that contains
N values evenly spaced from xstart to xstop. You can use the zeros
function to create a zero­filled vector of the right size. Use help zeros to
find out how the function works. 

[edit]

The while loop 
The while loop also executes a block of code more than once but stops based on a
logical condition. For example 
x = 1.0;
while x < 1000
x = x*2;
disp(x);
endwhile

will multiply x by 2 until its value exceeds 1000. Here, x < 1000 is the condition


of the loop. As long as the condition holds (is true), the loop will continue executing.
As soon as it is false, the loop terminates and the first instruction after the loop is
executed. 
The general form of a while loop is 
while condition
...
endwhile

[edit]

Exercise 
1. Write a script that calculates the smallest positive integer, n, such that
 for some real numbers a and b. (Meaning, find the smallest power of
a that is at least b.) Using the log function is considered cheating. 
[edit]

Example: The Mandelbrot fractal 
The Mandelbrot fractalThe Mandelbrot set is another fractal and is generated by
checking how long it takes a complex number to become large. For each complex
number, c, 
1. Start with z0 = 0. 

2. Let   
3. Find the first i such that | zi | > 2. 

We record all of these i values and assign a colour to each of them. This is used to
generate an image like this one. 

You can download the code that generates this fractal from Mandelbrot.m. Note that
there is a while loop (inside some for loops) that tests whether the complex number z
has modulus less than 2: 
while (count < maxcount) & (abs(z) < 2)
...
endwhile

The first condition in the while loop checks that we do not perform too many
iterations. For some values of c the iteration will go on forever if we let it. 
[edit]

The do...until statement 
These loops are very similar to while loops in that they keep executing based on
whether a given condition is true or false. There are however some important
difference between while and do...until loops. 
1. while loops have their conditions at the beginning of the loop;
do...until loops have theirs at the end. 
2. while loops repeat as long as the condition is true;
do...until loops continue as long as theirs is false. 
3. while will execute 0 or more times (because the condition is at the
beginning);
do...until loops will execute 1 or more times (since the condition is at the
end). 
The general form of a do...until loop is 
do
...
until condition

[edit]

Exercise 
Write a script that calculates the greatest common divisor (GCD) of two positive
integers. You can do this using Euclid's algorithm. 
[edit]

Challenge 
Write a script that generates random number pairs (a, b) that are distributed uniformly 

1. over the disc   (the first image below); 
2. as in the second image below 

 
[edit]

The break and continue statements 
Sometimes it is necessary to stop a loop somewhere in the middle of its execution or
to move on to the next value in a for loop without executing the rest of the loop code
for the current value. This is where the break and continue statements are useful. 
The following code demonstrates how the break statement works. 
total = 0;
while true
x = input('Value to add (enter 0 to stop): ');
if x == 0
break;
endif
total = total+x;
disp(['Total: ', num2str(total)]);
endwhile

Without the break statement, the loop would keep executing forever since the
condition of the while loop is always true. The break allows you to jump past the
end of the loop (to the statement after the endwhile). 
The break statement can be used in any loop: for, while or do...until. 
The continue statement also jumps from the inside of a loop but returns to the
beginning of the loop rather than going to the end. In a 
1. for loop, the next value inside the vector will be assigned to the for variable
(if there are any left) and the loop restarted with that value; 
2. while loop, the condition at the beginning of the loop will be retested and the
loop continued if it is still true; 
3. do...until loop, the condition at the end of the loop will be tested and the
loop continued from the beginning if it is still false. 
As an example, the following code will fill the lower triangular part of a square matrix
with 1s and the rest with 0s. 
N = 5;
A = zeros(N); % Create an N x N matrix filled with 0s

for row = 1:N


for column = 1:N
if column > row
continue;
endif
A(row, column) = 1;
endfor
endfor

disp(A);

Note that the inner for skips (continues) over the code that assigns a 1 to an entry of
A whenever the column index is greater than the row index. 
[edit]

The if statement 
The general form of the if statement is 
if condition1
...
elseif condition2
...
else
...
endif

If condition1 evaluates to true, the statements in the block immediately following
the if are executed. If condition1 is false, the next condition (condition2 in
the elseif) is checked and its statements executed if it is true. You can have as
many elseif statements as you like. The final set of statements, after the else, is
executed if all of the conditions evaluate to false. Note that the elseif and else
parts of the if statement are optional. 
The following are all valid if statements: 
% Take the log of the absolute value of x
if x > 0
y = log(x);
elseif x < 0
y = log(-x);
else
disp("Cannot take the log of zero.");
endif

x = input("Enter a value: ");


if x > 0
disp("The number is positive");
endif

if x < 0
disp("The number is negative");
endif

if x == 0
disp("The number is zero");
endif

[edit]

Example: The fractal fern 
This algorithm is not quite complete. Have a look at the .m file available from
http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=4372&
objectType=file. 
The image to the right can be generated with the following algorithm: 
1. Let x1 and y1 be random values between 0 and 1.
2. Choose one of the linear transformations below to calculate
(xi+1, yi+1) from (xi, yi):
1. xi+1 = 0
yi+1 = 0.16yi
2. xi+1 = 0.20xi − 0.26yi
yi+1 = 0.23xi + 0.22yi + 1.6
3. xi+1 = −0.15xi + 0.28yi
yi+1 = 0.26xi + 0.24yi + 0.44
4. xi+1 = 0.85xi + 0.04yi
yi+1 = −0.04xi + 0.85yi + 1.6
The first transformation is chosen if probability 0.01, the
second and third with probability 0.07 each and the fourth with
probability 0.85.
3. Calculate these values for i up to at least 10,000.

You can download the code that generates this fractal as fracfern.m (this is disabled
for now). 

Octave:Linear algebra
From AIMSWiki

[edit]

Functions 
● det(A) computes the determinant of the matrix A. 
● lambda = eig(A) returns the eigenvalues of A in lambda, and 
● [V, lambda] = eig(A) also returns the eigenvectors in V. 
● inv(A) computes the inverse of matrix A. Note that calculating the inverse is
often 'not' necessary. See the next two operators as examples. 
● A / B computes X such that XB = A. This is called right division and is done
without forming the inverse of B. 
● A \ B computes X such that AX = B. This is called left division and is done
without forming the inverse of A. 
● norm(A, p) computes the p­norm of the matrix (or vector) A. The second
argument is optional with default value p = 2. 
● rank(A) computes the (numerical) rank of a matrix. 
● trace(A) computes the trace (sum of the diagonal elements) of A. 
● expm(A) computes the matrix exponential of a square matrix. This is defined
as 

● logm(A) computes the matrix logarithm of a square matrix. 
● sqrtm(A) computes the matrix square root of a square matrix. 

Below are some more linear algebra functions. Use help to find out more about
them. 
● balance (eigenvalue balancing), 
● cond (condition number), 
● dmult (computes diag(x) * A efficiently), 
● dot (dot product), 
● givens (Givens rotation), 
● kron (Kronecker product), 
● null (orthonormal basis of the null space), 
● orth (orthonormal basis of the range space), 
● pinv (pseudoinverse), 
● syl (solves the Sylvester equation). 
[edit]

Factorizations 
● R = chol(A) computes the Cholesky factorization of the symmetric
positive definite matrix A, i.e. the upper triangular matrix R such that RTR = A. 
● [L, U] = lu(A) computes the LU decomposition of A, i.e. L is lower
triangular, U upper triangular and A = LU. 
● [Q, R] = qr(A) computes the QR decomposition of A, i.e. Q is
orthogonal, R is upper triangular and A = QR. 

Below are some more available factorizations. Use help to find out more about
them. 
● qz (generalized eigenvalue problem: QZ decomposition), 
● qzhess (Hessenberg­triangular decomposition), 
● schur (Schur decomposition), 
● svd (singular value decomposition), 
● housh (Householder reflections), 
● krylov (Orthogonal basis of block Krylov subspace). 

Octave:Polynomials
From AIMSWiki

In Octave, a polynomial is represented by its coefficients (arranged in descending
order). For example, the vector 
octave:1> p = [-2, -1, 0, 1, 2];

represents the polynomial 
− 2x4 − x3 + x + 2.
You can check this by displaying the polynomial with the function polyout. 
octave:2> polyout(p, 'x')
-2*x^4 - 1*x^3 + 0*x^2 + 1*x^1 + 2

The function displays the polynomial in the variable specified (x in this case). Note
that the ^ means raised to the power of much like the Octave operator. 
[edit]
Functions 
● Evaluating a polynomial: 
y = polyval(p, x)

This returns p(x). If x is a vector or matrix, the polynomial is evaluated at each of the
elements of x. 
● Multiplication: 
r = conv(p, q)

Here, p and q are vectors containing the coefficients of two polynomials and the
result, r, will contain the coefficients of their product. 
(As an aside, the reason why this function is called conv is that we use vector
convolution to do polynomial multiplication.) 
● Division: 
[b, r] = deconv(y, a)

This returns the coefficients of the polynomials b and r such that 
y = ab + r.
So, b contains the coefficients of the quotient and r the coefficients of the remainder
of y and a . 
● Root finding: 
roots(p)

This returns a vector containing all the roots of the polynomial with coefficients in p. 
● Derivative: 
q = polyderiv(p)

This returns the coefficients of the derivative of the polynomial whose coefficients are
given by vector p. 
● Integration: 
q = polyinteg(p)

This returns the coefficients of the integral of the polynomial whose coefficients are
represented by the vector p. The constant of integration is set to 0. 
● Data fitting: 
p = polyfit(x, y, n)

This returns the coefficients of a polynomial p(x) of degree n that best fits the data
(xi,yi) in the least squares sense. 
[edit]

Warning: Adding polynomials 
Since polynomials are represented by vectors of their coefficients, adding polynomials
is not straightforward in Octave. For example, we define the polynomials p(x) = x2 −
1 and q(x) = x + 1. 
octave:1> p = [1, 0, -1];
octave:2> q = [1, 1];

If we try to add them, we get 
octave:3> p + q
error: operator +: nonconformant arguments (op1 is 1x3, op2 is 1x2)
error: evaluating binary operator `+' near line 22, column 3

This happens because Octave is trying to add two vectors (p and q) of different
lengths. This operation is not defined. To work around this, you have to add some
leading zeroes to q. 
octave:4> q = [0, 1, 1];

Note that adding leading zeroes does not change the polynomial. Next, we add 
octave:5> p + q
ans =

1 1 0

octave:6> polyout(ans, 'x')


1*x^2 + 1*x^1 + 0

Octave:Sets
From AIMSWiki

Table of contents [showhide] 
1 Creating a set
2 Manipulating sets

Octave implements some 'very' basic set operations. Sets are implemented as ordered
vectors and, for this reason, the set functions may also be useful for 
● sorting and 
● finding unique elements in 
a vector. 
[edit]
Creating a set
You can create an empty set by using an empty vector: 
octave:1> A = [];

This is often a good place to start and you can use the functions for manipulating sets
(see the next section) to add elements to this. 
You can also create a set from a vector using 
octave:2> A = create_set(x);

Here, x is a vector or matrix and the result, stored in A contains unique values from x
sorted in ascending order. For example, 
octave:3> create_set([1, 2; 3, 4; 4, 2])
ans =

1 2 3 4

[edit]

Manipulating sets

The three set operations union,  , intersection,   and

complement,   are implemented in Octave and behaves in the normal way.
The commands for these functions are 
● union(a, b) returns a set of elements that are in at least one of a and b 
● intersection(a, b) returns the elements that are in both a and b 
● complement(a, b) returns the elements from b that are not in a (this is
actually the set difference, B / A, but can be thought of as the complement of A
if B is the universe of elements) 
The following examples illustrate the functions. 
octave:4> u = create_set([1, 10, 5, 2, 4])
u =

1 2 4 5 10

octave:5> v = create_set([3, 4, 5, 6])


v =

3 4 5 6

octave:6> union(u, v)
ans =

1 2 3 4 5 6 10
octave:7> intersection(u, v)
ans =

4 5

octave:8> complement(u, [1:10])


ans =

3 6 7 8 9

lsode is the dynamically­linked function from the file
/usr/lib/octave/2.1.64/oct/i386­pc­linux­gnu/lsode.oct

 ­­ Loadable Function: [X, ISTATE, MSG] lsode (FCN, X_0, T, T_CRIT)
     Solve the set of differential equations

          dx
          ­­ = f(x, t)
          dt

     with

          x(t_0) = x_0

     The solution is returned in the matrix X, with each row
     corresponding to an element of the vector T.  The first element of
     T should be t_0 and should correspond to the initial state of the
     system X_0, so that the first row of the output is X_0.

     The first argument, FCN, is a string that names the function to
     call to compute the vector of right hand sides for the set of
     equations.  The function must have the form

          XDOT = f (X, T)

     in which XDOT and X are vectors and T is a scalar.

     If FCN is a two­element string array, the first element names the
     function f described above, and the second element names a function
     to compute the Jacobian of f.  The Jacobian function must have the
     form

          JAC = j (X, T)

     in which JAC is the matrix of partial derivatives
                       | df_1  df_1            df_1 |
                       | ­­­­     ­­­­   ...         ­­­­ |
                       | dx_1  dx_2         dx_N |
                     
                                     | df_2    df_2          df_2    |
                                     | ­­­­        ­­­­  ...       ­­­­    |
                df_i               | dx_1   dx_2         dx_N   |
          jac = ­­­­ =          |                                         |
                dx_j              |  .    .     .    .                      |
                                     |  .    .      .   .                      |
                                     |  .    .       .  .                      |
                                     |                                         |
                                     | df_N     df_N         df_N  |
                                     | ­­­­  ­­­­            ...     ­­­­   |
                                     | dx_1    dx_2          dx_N  |

     The second and third arguments specify the intial state of the
     system, x_0, and the initial value of the independent variable t_0.

     The fourth argument is optional, and may be used to specify a set
     of times that the ODE solver should not integrate past.  It is
     useful for avoiding difficulties with singularities and points
     where there is a discontinuity in the derivative.

     After a successful computation, the value of ISTATE will be 2
     (consistent with the Fortran version of LSODE).

     If the computation is not successful, ISTATE will be something
     other than 2 and MSG will contain additional information.

     You can use the function `lsode_options' to set optional
     parameters for `lsode'.
   See also: daspk, dassl, dasrt, odessa.

You might also like