Getting Started with Octave

Running Code

We will rely on the Octave Kernel for Jupyter Notebook for running code and visualization for this tutorial.

You can use Octave from the terminal, with a jupyter notebook or via the OctaveGUI application. Octave provides you with a Read-Eval-Print-Loop - short REPL - where you can run your commands.

Getting help

You can consult the documentation of a function by typing help followed by the function name.

Example:

In [ ]:
help log

Good to know

  • 1-based indexing
  • Matlab compatible (somewhat, always try your code first when changing systems. Usually there are some issues)
  • variable-length argument lists
  • variable-length return lists

Getting Started

real and complex scalars and matrices, character strings, a data structure type, and an array that can contain all data types see

real and complex scalars

In [ ]:
realScalar = 5
In [ ]:
complexScalar = 5 + 2i;

When appending a semicolon ; the output will be omitted. Typing the variable name will output its value:

In [ ]:
complexScalar

matrices

In [ ]:
rowVector = [1 2 3 4 5]
In [ ]:
rowVector = 1:5
In [ ]:
colVector = [1; 2; 3; 4; 5]
In [ ]:
colVector = (1:5)'
In [ ]:
# compare to
colVector = 1:5'

The ' in this example stands for transpose. Octave will transpose the respective vector. Be careful how it's interpreted by Octave though.

In [ ]:
matrix = [1 2 3; 4 5 6; 7 8 9]

You can also work with complex matrices (won't be covered in this course, hence omitted here).

index expressions

In [ ]:
a = [1:2; 3:4]
In [ ]:
a(2)       # result is a scalar
a(1:2)     # result is a row vector
a([1; 2])  # result is a column vector
In [ ]:
a(:)       # result is a column vector
a(:)'      # result is a row vector
In [ ]:
a(1, [1, 2])  # row 1, columns 1 and 2
a(1, 1:2)     # row 1, columns in range 1-2
a(1, :)       # row 1, all columns
In [ ]:
a = [1, 2, 3, 4];

a(1:end/2)        # first half of a => [1, 2]
a(end + 1) = 5;   # append element
a(end) = [];      # delete element
a(1:2:end)        # odd elements of a => [1, 3]
a(2:2:end)        # even elements of a => [2, 4]
a(end:-1:1)       # reversal of a => [4, 3, 2 , 1]

special utility matrices

In [ ]:
eye(3)
In [ ]:
ones(3)
In [ ]:
zeros(3)
In [ ]:
rand(3)

for more see here

character strings

You can use both single '' and double parentheses "" for defining strings. String will probably only important when setting the labels for your figures.

In [ ]:
string_1 = 'abc'
In [ ]:
string_2 = "abc"

data structure type

In [ ]:
strct.scalar = 1;
strct.matrix = [1, 2; 3, 4];
strct.string = "string";
In [ ]:
strct

cell arrays

In [ ]:
c = {"a string", rand(2, 2)};
In [ ]:
c{1}
In [ ]:
c{2}
In [ ]:
c{1:2}

Arithmetic Operations

In [ ]:
a = (1:4)'

Dot-Product $a^{T}a$

In [ ]:
a' * a

Outer Product - $aa^{T}$

In [ ]:
a * a'
In [ ]:
A = [1 2; 3 4]

Matrix Multiplication - $AA$

In [ ]:
A * A

Dimensions must match!

In [ ]:
B = [1 2 3; 4 5 6]
In [ ]:
B * A

Matrix Vector Multiplication - $Xb$

In [ ]:
X = [1:3; 4:6; 7:9]
b = [1; 1; 1]
In [ ]:
X*b

Octave also features functions from Linear Algebra for LU or QR decomposition, linear systems solvers, etc.

You can find more about that here

Plotting

In [ ]:
graphics_toolkit("gnuplot")

run this command if the plots are black

In [ ]:
%plot --format svg
In [ ]:
x = rand(5, 1)

1-dimensional

In [ ]:
plot(x)
In [ ]:
x = rand(100, 1);
y = rand(100, 1);

2-dimensional

In [ ]:
plot(x, y, '.')
In [ ]:
x = linspace(0, 2*pi, 50);
y = sin(x);
plot(x, y, '+1;sin(x);');
In [ ]:
x = linspace(0, 2*pi, 100);
y = sin(x);
y2 = cos(x);
plot(x, y, '+1;sin(x);', "markersize", 10, x, y2, ";cos(x);", "markersize", 5, "marker", '*');
In [ ]:
plot(x, y, '+1;sin(x);', "markersize", 10);
hold on         # <--- will keep your current plot
plot(x, y2, ";cos(x);", "markersize", 5, "marker", '*')

Nice! Unfortunately we are still missing labels. A different colorscheme and lines instead of the the points would also be nice. So back to the plotting board:

In [ ]:
plot(
    x, y,  "-;sin(x);",  "color", [27,158,119] ./255, "linewidth", 5,
    x, y2, "--;cos(x);", "color", [117,112,179] ./255, "linewidth", 5);
set(gca, 'xtick', [0, pi, 2*pi])
#set(gca, 'xticklabel', {'0', '\pi', '2 \pi'}) # <--- should work, maybe a bug 
set(gca, 'interpreter', 'tex')
xlabel('{\fontsize{30} \pi}')
ylabel('{\fontsize{30} value}')
title('{\fontsize{50} Sinus and Cosinus}')

plot matrix columns as multiple lines

In [ ]:
X = randn(10, 4)
In [ ]:
plot(X)

Programming

Control Structures

if - Statement

In [ ]:
a = 5
if a > 3
    disp([num2str(a),' is larger than 3'])
elseif a < 3
    disp([num2str(a),' is smaller than 3'])
else
    disp([num2str(a),' is equal to 3'])
end

switch - Statement

In [ ]:
animal = 'cow'

switch animal
    case 'dog'
        disp('Woof')
    case 'cat'
        disp('Meow')
    case 'bird'
        disp('Tweep')
    otherwise
    disp(['Error: no sound available for animal ', animal])
end

while - Statement

In [ ]:
x = 2
while x < 16
    x = x*2
end

break - statement

In [ ]:
for i = 1:5
    i
end

Incrementing Operators (Octave only!)

In [ ]:
i = 1
i++                  # <--- what's happening here?
++i
In [ ]:
A = zeros(2,2)
A++                  # <--- what's happening here?
In [ ]:
A--
A

Comparison operators

All of comparison operators return a value of 1 if the comparison is true, or 0 if it is false.

In [ ]:
1 != 3

matrix-to-matrix

In [ ]:
[1 2; 3 4] == [1 4; 2 3]

matrix to vector (by row and by column)

In [ ]:
[1 2; 1 2] == [1 2]
In [ ]:
[1 2; 1 2] == [1 2]'

matrix to scalar

In [ ]:
[1 2; 3 4] == 1

Comparison Operators

In [ ]:
v = ones(1, 10)

any - returns 1 if any element of vector v is non-zero

In [ ]:
any(v)

all - returns 1 if all elements of vector are non-zero

In [ ]:
all(v)

for matrices, any and all return a row vector with elements corresponding to the columns of the matrix

In [ ]:
A = ones(4)
In [ ]:
any(any(A))
In [ ]:
all(all(A))

Relational Operators

In [ ]:
x = 1
y = 2
x < y          #true if x less than y
x <= y         #true if x less thon or equal y
x == y         #true if x equal to y
x >= y         #true if x greater thon or equal y
x > y          #true if X greater than y
x ~= y         #true if x not equal to y
x ~= y         #true if x not equal to y (Octave only)

Boolean Expressions

In [ ]:
B1 = true
B2 = false
B1 & B2        #element-wise logical and
B1 | B2        #element-wise logical or
~B1            #element-wise logical not
!B1            #element-wise logical not (Octave only)

Functions and Scripts

Function definition in Octave

function name
    body
end

It's good practice to define one function per file (m-file or .m-file)

function parameters Functions usually have one or more parameters and might return multiple results

function [ret-vars] = name (arg-list)
    body
end
In [ ]:
function b = gemv (A, v)
    b = A*v;
end
In [ ]:
gemv(ones(4), (1:4)')
In [ ]:
function [_min _max] = calc_extremas(data)
    _min = min(data);
    _max = max(data);
end
In [ ]:
[mi, ma] = calc_extremas(rand(10,1))
In [ ]: