Introduction To GNU Octave
Introduction To GNU Octave
Date: 2008/08/16
Contents
• 1 Basics
◦ 1.1 What is Octave?
◦ 1.2 Help!
◦ 1.3 Input conventions
◦ 1.4 Variables and standard operations
1 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
• 3 Control structures
◦ 3.1 Functions
◦ 3.2 Global variables
◦ 3.3 Loops
◦ 3.4 Branching
◦ 3.5 Functions of functions
◦ 3.6 Efficiency considerations
◦ 3.7 Input and output
• 4 Graphics
◦ 4.1 2D graphics
◦ 4.2 3D graphics:
◦ 4.3 Commands for 2D and 3D graphics
• 5 Exercises
◦ 5.1 Linear algebra
◦ 5.2 Timing
◦ 5.3 Stability functions of BDF-integrators
◦ 5.4 3D plot
◦ 5.5 Hilbert matrix
◦ 5.6 Least square fit of a straight line
◦ 5.7 Trapezoidal rule
1 Basics
1.1 What is Octave?
Octave is an interactive programming language specifically suited for vectorizable numerical calculations. It
provides a high level interface to many standard libraries of numerical mathematics, e.g. LAPACK or BLAS.
The syntax of Octave resembles that of Matlab. An Octave program usually runs unmodified on Matlab.
Matlab, being commercial software, has a larger function set, and so the reverse does not always work,
especially when the program makes use of specialized add-on toolboxes for Matlab.
1.2 Help!
• help lists the names of all built-in functions and internal variables.
• help name further explains the variable or function ``name''.
Example:
2 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
• whos shows all user-defined variables and functions (see Section 3.1).
• clear name clears name from memory; if no name is given, all variables and functions will be cleared.
• type name displays information about the variable or function name on the screen.
Examples:
3 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
2.1 Vectors
• Row vector: :
v = [ 1 2 3 ]
• Column vector: :
v = [ 1; 2; 3 ]
Start[:Increment]:End
Examples:
octave:1> x = 3:6
x =
3 4 5 6
octave:2> y = 0:.15:.7
y =
0.00000 0.15000 0.30000 0.45000 0.60000
octave:3> z = pi:-pi/4:0
z =
3.14159 2.35619 1.57080 0.78540 0.00000
2.2 Matrices
octave:1> A = [ 1 2; 3 4]
A =
1 2
3 4
4 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
1 2 5
3 4 6
There are functions to create frequently used matrices. If , only one argument is necessary.
• eye(m,n) produces a matrix with ones on the main diagonal and zeros elsewhere. When , the
identity matrix is generated.
• zeros(m,n) generates the zero matrix of dimension .
• ones(m,n) generates an matrix where all entries are .
• rand(m,n) generates a random matrix whose entries are uniformly distributed in the interval .
Examples:
Examples:
1 4
9 16
7 10
15 22
5 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
Querying dimensions:
Reshaping:
Examples:
1 2 3
4 5 8
octave:3> A(:,2) = v
A =
1 7 3
4 8 8
7 8 3
4 8 8
6 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
A lot of these commands support further options. They can be listed by typing help funcname.
3 Control structures
3.1 Functions
Traditionally, functions are also stored in plain text files with suffix .m. In contrast to scripts, functions can be
called with arguments, and all variables used within the function are local--they do not influence variables
defined previously.
Example:
Remark:
In Octave, several functions can be defined in a single script file. Matlab on the other hand, strictly enforces
one function per .m file, where the name of the function must match the name of the file. If compatibility with
Matlab is important, this restriction should also be applied to programs written in Octave.
7 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
Obviously, the variables out1 and out2 were local to dolittle. Previously defined variables out1 or out2
would not have been affected by calling dolittle.
Example:
3.3 Loops
The syntax of for- and while-loops is immediate from the following examples:
for n = 1:10
[x(n),y(n)]=dolittle(n);
end
while t<T
t = t+h;
end
8 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
For-loop backward:
for n = 10:-1:1
...
3.4 Branching
Conditional branching works as follows.
if x==0
error('x is 0!');
else
y = 1/x;
end
switch pnorm
case 1
sum(abs(v))
case inf
max(abs(v))
otherwise
sqrt(v'*v)
end
Example:
function S = mpr(fun,a,b,N)
h = (b-a)/N;
S = h*sum(feval(fun,[a+h/2:h:b]));
end
9 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
Loops and function calls, especially through feval, have a very high computational overhead. Therefore, if
possible, vectorize all operations.
Example:
We are programming the midpoint rule from the previous section with a for-loop (file name is mpr_long.m):
function S = mpr_long(fun,a,b,N)
h = (b-a)/N; S = 0;
for k = 0:(N-1),
S = S + feval(fun,a+h*(k+1/2));
end
S = h*S;
end
We verify that mpr and mpr_long yield the same answer, and compare the evaluation times.
octave:1> t = cputime;
> Int1=mpr('gauss',0,5,500); t1=cputime-t;
octave:2> t = cputime;
> Int2=mpr_long('gauss',0,5,500); t2=cputime-t;
octave:3> Int1-Int2, t2/t1
ans = 0
ans = 45.250
Example:
4 Graphics
4.1 2D graphics
• plot(x,y[,fmt]) plots a line through the points . With the string fmt you can select line style
and color; see help plot for details.
• semilogx(x,y[,fmt]) like plot with a logarithmic scale for the axis.
• semilogy(x,y[,fmt]) like plot with a logarithmic scale for the axis.
10 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
Important: Since operates element-wise, you must use of the operators .+, .-, .^ etc. instead of the
usual +, - and ^! (See Section 2.4.)
3. Finally you call the plot command.
plot(x,y)
Example:
octave:1> x = -10:.1:10;
octave:2> y = sin(x).*exp(-abs(x));
octave:3> plot(x,y)
octave:4> grid
4.2 3D graphics:
11 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
• [xx,yy] = meshgrid(x,y) generates the grid data for a 3D plot--two matrices xx whose rows are copies
of x, and yy whose columns are copies of y.
• mesh(x,y,z) plots a surface in 3D.
Example:
octave:1> x = -2:0.1:2;
octave:2> [xx,yy] = meshgrid(x,x);
octave:3> z = sin(xx.^2-yy.^2);
octave:4> mesh(x,x,z);
5 Exercises
5.1 Linear algebra
Take a matrix and a vector with
12 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
and
Solve the system of equations . Calculate the LU and QR decompositions, and the eigenvalues and
eigenvectors of . Compute the Cholesky decomposition of , and verify that
.
Solution:
5.2 Timing
Compute the matrix-vector product of a random matrix with a random vector in two different
ways. First, use the built-in matrix multiplication *. Next, use for-loops. Compare the results and computing
times.
Solution:
A = rand(100); b = rand(100,1);
t = cputime;
v = A*b; t1 = cputime-t;
w = zeros(100,1);
t = cputime;
for n = 1:100,
for m = 1:100
w(n) = w(n)+A(n,m)*b(m);
end
end
t2 = cputime-t;
norm(v-w), t2/t1
13 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
Plot these roots as points in the complex plane and draw a unit circle for comparison. (Hint: hold, real,
imag).
Solution:
5.4 3D plot
Plot the graph of the function
Solution:
x = -3:0.1:3;
[xx,yy] = meshgrid(x,x);
z = exp(-xx.^2-yy.^2);
figure, mesh(x,x,z);
title('exp(-x^2-y^2)');
14 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
Solution:
Solution:
For a function of your choice, check, by generating a doubly logarithmic error plot, that the trapezoidal
rule is of order .
Solution:
15 of 16 8/10/2022, 11:19 AM
Introduction to GNU Octave http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/oc...
function S = trapez(fun,a,b,N)
h = (b-a)/N;
% fy = feval(fun,[a:h:b]); better:
fy = feval(fun,linspace(a,b,N+1));
fy(1) = fy(1)/2;
fy(N+1) = fy(N+1)/2;
S = h*sum(fy);
end
function y = f(x)
y = exp(x);
end
for k=1:15;
err(k) = abs(exp(1)-1-trapez('f',0,1,2^k));
end
loglog(1./2.^[1:15],err);
hold on;
title('Trapezoidal rule, f(x) = exp(x)');
xlabel('Increment');
ylabel('Error');
loglog(1./2.^[1:15],err,'x');
16 of 16 8/10/2022, 11:19 AM