Complete Beginner's Guide

GNU Octave

From zero to numerical computing — one section at a time.

15 sections Code examples Progress tracking Free & Open Source
01

What is Octave?

GNU Octave is a free, open-source programming language designed primarily for numerical computation. It is largely compatible with MATLAB, making it a popular free alternative in academia, engineering, and science.

What can you do with it?

💡 Good to knowOctave code is mostly compatible with MATLAB — skills you learn here transfer directly.
02

Installation

Windows

Go to https://octave.org/download, download the .exe installer, and run it.

macOS

Using Homebrew:

$ brew install octave

Or download the .dmg from the official website.

Linux (Ubuntu / Debian)

$ sudo apt update
$ sudo apt install octave

Verify Installation

$ octave --version
03

The Octave Interface

When you launch Octave, you'll see several panels:

PanelDescription
Command WindowWhere you type commands and see output
WorkspaceShows all currently defined variables
Command HistoryA log of all commands you've entered
File BrowserNavigate your filesystem
EditorWrite and save .m script files
💡 TipYou can run Octave from the terminal by typing octave (CLI mode) or octave --gui for the graphical interface.
04

Basic Arithmetic & the Command Line

The Command Window works like a powerful calculator. Type an expression and press Enter.

>> 2 + 3
ans = 5

>> 10 - 4
ans = 6

>> 3 * 7
ans = 21

>> 15 / 4
ans = 3.7500

>> 2 ^ 8        % Exponentiation
ans = 256

>> mod(17, 5)   % Modulo (remainder)
ans = 2

Suppressing Output

Add a semicolon (;) at the end of a line to suppress its output:

>> x = 42;    % No output shown
>> x          % Now show it
x = 42

Comments

Use % to write comments (Octave ignores everything after it):

>> 5 + 3   % This adds 5 and 3
05

Variables

Variables store data for later use. Octave is case-sensitivemyVar and myvar are different variables.

>> x = 10
x = 10

>> name = "Alice"
name = Alice

>> pi_approx = 3.14159
pi_approx = 3.1416

Naming Rules

Workspace Commands

who          % List all variables
whos         % List variables with size and type
clear x     % Delete variable x
clear        % Delete ALL variables
06

Data Types

TypeExampleDescription
double3.14Default numeric type (floating point)
int32int32(5)32-bit integer
char'hello'Single-quoted string (character array)
string"hello"Double-quoted string
logicaltrue, falseBoolean values
cell{1, "hi", [1 2]}Array holding mixed types
structs.name = "Bob"Named fields (like a record)
>> class(3.14)
ans = double

>> class("hello")
ans = char

>> class(true)
ans = logical
07

Vectors and Matrices

Matrices are the core data structure in Octave. A vector is simply a 1-row or 1-column matrix.

Creating Vectors

% Row vector (spaces or commas)
>> v = [1 2 3 4 5]
v = 1   2   3   4   5

% Column vector (semicolons)
>> c = [10; 20; 30]
c =
   10
   20
   30

Ranges

>> 1:5            % 1 to 5, step 1
ans = 1   2   3   4   5

>> 0:0.5:2        % 0 to 2, step 0.5
ans = 0.0000   0.5000   1.0000   1.5000   2.0000

>> 10:-2:2        % Count down
ans = 10   8   6   4   2

Creating Matrices

>> A = [1 2 3; 4 5 6; 7 8 9]
A =
   1   2   3
   4   5   6
   7   8   9

Useful Matrix Builders

zeros(3, 3)       % 3×3 matrix of zeros
ones(2, 4)        % 2×4 matrix of ones
eye(4)            % 4×4 identity matrix
rand(3)           % 3×3 random values (0–1)
linspace(0,1,5)  % 5 evenly spaced points from 0 to 1

Indexing

📌 NoteOctave uses 1-based indexing — the first element is index 1, not 0.
>> v = [10 20 30 40 50];
>> v(1)           % First element → 10
>> v(end)         % Last element  → 50
>> v(2:4)         % Elements 2–4  → 20 30 40

>> A(2, 3)        % Row 2, Col 3
>> A(1, :)        % Entire first row
>> A(:, 2)        % Entire second column

Size Commands

size(A)       % [rows, cols]
rows(A)       % Number of rows
columns(A)   % Number of columns
length(v)    % Length of a vector
numel(A)     % Total number of elements
08

Matrix Operations

OperatorMeaning
A + BElement-wise addition
A - BElement-wise subtraction
A * BMatrix multiplication
A ^ 2Matrix power (A × A)
A'Transpose
A .* BElement-wise multiplication
A ./ BElement-wise division
A .^ 2Element-wise squaring
⚠️ Key Distinction* is matrix multiplication. .* is element-by-element multiplication. This is one of the most common beginner mistakes.
>> A = [1 2; 3 4];
>> B = [5 6; 7 8];

>> A * B           % Matrix multiply
ans =
   19   22
   43   50

>> A .* B          % Element-wise multiply
ans =
    5   12
   21   32

Linear Algebra

det(A)       % Determinant
inv(A)       % Inverse
rank(A)      % Rank
eig(A)       % Eigenvalues (and eigenvectors)
A \ b        % Solve Ax = b (better than inv(A)*b)
09

Built-in Functions

Math

sqrt(16)      % → 4
abs(-5)       % → 5
floor(3.7)   % → 3  (round down)
ceil(3.2)    % → 4  (round up)
round(3.5)   % → 4  (round nearest)
log(exp(1))  % Natural log → 1
log2(8)     % → 3
log10(100)  % → 2
exp(1)       % e¹ ≈ 2.7183

Trigonometry (radians)

sin(pi/2)    % → 1
cos(0)       % → 1
tan(pi/4)   % → 1
asin(1)     % → pi/2

Statistics

v = [4 7 2 9 1 5];
sum(v)       % Sum of elements
mean(v)      % Average
median(v)   % Median
std(v)       % Standard deviation
var(v)       % Variance
min(v)       % Minimum
max(v)       % Maximum
sort(v)      % Sort ascending
cumsum(v)   % Cumulative sum
10

Control Flow

if / elseif / else

x = 15;

if x > 20
  disp("x is greater than 20");
elseif x > 10
  disp("x is between 10 and 20");
else
  disp("x is 10 or less");
end

Comparison & Logical Operators

OperatorMeaning
==Equal to
~=Not equal to
< / >Less / greater than
<= / >=Less / greater or equal
&&Logical AND (scalars)
||Logical OR (scalars)
! or ~Logical NOT

for Loop

for i = 1:5
  printf("i = %d\n", i);
end

while Loop

n = 1;
while n <= 5
  disp(n);
  n = n + 1;
end

break and continue

for i = 1:10
  if i == 4
    continue;    % Skip this iteration
  end
  if i == 7
    break;       % Exit the loop
  end
  disp(i);
end
% Prints: 1, 2, 3, 5, 6
11

Functions

Functions are reusable blocks of code. Save them in their own .m file with the same name as the function.

Basic Function (save as add_numbers.m)

function result = add_numbers(a, b)
  result = a + b;
end
>> add_numbers(3, 7)
ans = 10

Multiple Return Values

function [mn, mx] = min_max(v)
  mn = min(v);
  mx = max(v);
end
>> [lo, hi] = min_max([3 1 9 4]);
>> lo
lo = 1
>> hi
hi = 9

Anonymous Functions

Quick one-liner functions using the @ symbol:

>> square = @(x) x.^2;
>> square(5)
ans = 25

>> f = @(x, y) x^2 + y^2;
>> f(3, 4)
ans = 25
12

Scripts (.m Files)

A script is a plain text file with a .m extension containing a sequence of Octave commands. Unlike functions, scripts share the base workspace.

How to create and run

  1. Open the Editor panel (or any text editor)
  2. Write your code and save as my_script.m
  3. Run from the Command Window: type my_script and press Enter

Example: circle_stats.m

% circle_stats.m — Circle area and circumference
radius = 7;

area = pi * radius^2;
circumference = 2 * pi * radius;

printf("Radius:        %.2f\n", radius);
printf("Area:          %.4f\n", area);
printf("Circumference: %.4f\n", circumference);
>> circle_stats
Radius:        7.00
Area:          153.9380
Circumference: 43.9823
13

Plotting & Visualization

Basic Line Plot

x = 0:0.1:2*pi;
y = sin(x);

plot(x, y);
title("Sine Wave");
xlabel("x (radians)");
ylabel("sin(x)");
grid on;

Line Style Options

CodeMeaningCodeMeaning
rRed-Solid line
bBlue--Dashed line
gGreenoCircle markers
kBlack*Star markers
plot(x, y, 'r--', 'LineWidth', 2);  % Red dashed, thicker

Multiple Lines

x = linspace(0, 2*pi, 100);
plot(x, sin(x), 'b-', x, cos(x), 'r--');
legend("sin(x)", "cos(x)");
grid on;

Subplots

subplot(2, 1, 1);       % 2 rows, 1 col, plot #1
plot(x, sin(x));  title("Sine");

subplot(2, 1, 2);       % 2 rows, 1 col, plot #2
plot(x, cos(x));  title("Cosine");

Other Plot Types

bar([3 7 2 5 9]);               % Bar chart
scatter(rand(1,50), rand(1,50));  % Scatter plot
hist(randn(1, 1000), 30);        % Histogram

% 3D surface
[X, Y] = meshgrid(-3:0.1:3, -3:0.1:3);
Z = sin(X) .* cos(Y);
surf(X, Y, Z);

Saving Figures

saveas(gcf, "my_plot.png");    % Save as PNG
print("my_plot.pdf", "-dpdf"); % Save as PDF
14

File I/O

Writing and Reading Text Files

% Write to a file
fid = fopen("data.txt", "w");
fprintf(fid, "Hello, World!\n");
fprintf(fid, "Value: %f\n", 3.14);
fclose(fid);

% Read a file line by line
fid = fopen("data.txt", "r");
line = fgetl(fid);
while ischar(line)
  disp(line);
  line = fgetl(fid);
end
fclose(fid);

CSV Files

% Save matrix to CSV
A = [1 2 3; 4 5 6; 7 8 9];
csvwrite("matrix.csv", A);

% Load CSV
B = csvread("matrix.csv");

Saving & Loading Variables

save("workspace.mat");            % Save all variables
save("results.mat", "x", "y");   % Save specific ones
load("workspace.mat");           % Reload them
15

Tips, Shortcuts & Cheat Sheet

Essential Commands

CommandDescription
help funcShow documentation for a function
doc funcOpen full documentation page
clcClear the Command Window
clearClear all variables
close allClose all figure windows
pwdPrint current working directory
cd /pathChange directory
lsList files in current directory

Keyboard Shortcuts

ShortcutAction
↑ / ↓Scroll command history
TabAutocomplete variable/function name
Ctrl+CCancel a running computation
Ctrl+LClear the screen

Vectorization — Write Faster Code

Avoid slow loops by letting Octave operate on entire vectors at once:

% Slow (loop)
for i = 1:1000
  y(i) = sin(i * 0.01);
end

% Fast (vectorized)
x = (1:1000) * 0.01;
y = sin(x);

Quick-Reference Cheat Sheet

Arithmetic

+ - * / ^ mod()

Comparison

== ~= < > <= >=

Logical

&& || ! ~

Matrix

[1 2; 3 4] A' A*B A.*B A\b

Ranges

start:step:end
linspace(a,b,n)

Indexing

v(i) A(r,c) A(1,:) A(:,2)

Control

if/elseif/else/end
for/end while/end

Functions

function y=f(x) ... end
f = @(x) x.^2

Plotting

plot(x,y) title() xlabel()
ylabel() grid on legend()

Output

disp() printf() fprintf()

Help

help func doc func

Workspace

who whos clear save load