GNU Octave
From zero to numerical computing — one section at a time.
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?
- Solve linear algebra problems
- Perform statistical analysis
- Plot graphs and visualizations
- Process signals and images
- Simulate mathematical models
- Write reusable scripts and functions
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
The Octave Interface
When you launch Octave, you'll see several panels:
| Panel | Description |
|---|---|
Command Window | Where you type commands and see output |
Workspace | Shows all currently defined variables |
Command History | A log of all commands you've entered |
File Browser | Navigate your filesystem |
Editor | Write and save .m script files |
octave (CLI mode) or octave --gui for the graphical interface.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
Variables
Variables store data for later use. Octave is case-sensitive — myVar and myvar are different variables.
>> x = 10
x = 10
>> name = "Alice"
name = Alice
>> pi_approx = 3.14159
pi_approx = 3.1416
Naming Rules
- Must start with a letter
- Can contain letters, numbers, and underscores
- Cannot use reserved words like
for,if,end
Workspace Commands
who % List all variables
whos % List variables with size and type
clear x % Delete variable x
clear % Delete ALL variables
Data Types
| Type | Example | Description |
|---|---|---|
double | 3.14 | Default numeric type (floating point) |
int32 | int32(5) | 32-bit integer |
char | 'hello' | Single-quoted string (character array) |
string | "hello" | Double-quoted string |
logical | true, false | Boolean values |
cell | {1, "hi", [1 2]} | Array holding mixed types |
struct | s.name = "Bob" | Named fields (like a record) |
>> class(3.14)
ans = double
>> class("hello")
ans = char
>> class(true)
ans = logical
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
>> 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
Matrix Operations
| Operator | Meaning |
|---|---|
A + B | Element-wise addition |
A - B | Element-wise subtraction |
A * B | Matrix multiplication |
A ^ 2 | Matrix power (A × A) |
A' | Transpose |
A .* B | Element-wise multiplication |
A ./ B | Element-wise division |
A .^ 2 | Element-wise squaring |
* 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)
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
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
| Operator | Meaning |
|---|---|
== | 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
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
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
- Open the Editor panel (or any text editor)
- Write your code and save as
my_script.m - Run from the Command Window: type
my_scriptand 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
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
| Code | Meaning | Code | Meaning |
|---|---|---|---|
r | Red | - | Solid line |
b | Blue | -- | Dashed line |
g | Green | o | Circle markers |
k | Black | * | 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
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
Tips, Shortcuts & Cheat Sheet
Essential Commands
| Command | Description |
|---|---|
help func | Show documentation for a function |
doc func | Open full documentation page |
clc | Clear the Command Window |
clear | Clear all variables |
close all | Close all figure windows |
pwd | Print current working directory |
cd /path | Change directory |
ls | List files in current directory |
Keyboard Shortcuts
| Shortcut | Action |
|---|---|
↑ / ↓ | Scroll command history |
Tab | Autocomplete variable/function name |
Ctrl+C | Cancel a running computation |
Ctrl+L | Clear 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\bRanges
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/endFunctions
function y=f(x) ... end
f = @(x) x.^2Plotting
plot(x,y) title() xlabel()
ylabel() grid on legend()Output
disp() printf() fprintf()Help
help func doc funcWorkspace
who whos clear save load