Getting Started in MATLAB/Octave#

MATLAB is a computational tool that allows for quick mathematical scripting and plotting. While Mr. Manning isn’t a particular fan of MATLAB (mainly because indexing starts at 1 for almost everything instead of 0 like a normal programing language), even he can’t deny the usability and quality plots it creates are very helpful in multiple situations.

Coming from Python, you will see a lot of similarities to MATLAB. Seting up scripts is very similar, and you will see a lot of similarities when setting up loops and functions, though there are minor syntax differences that will take some adjusting to. If you are already familiar with Python, learning another programming language won’t be too tricky for you. It is just like learning another verbal or written language. The general rules stay the same, but the nuances and syntax will change slightly, but once you know one language, picking up another tends to move a little smoother.

NOTE: All of the MATLAB interactive pages are going to look a little weird, I have no idea why. There is a bunch of junk whitespace that keeps getting made when it compiled for the website, and I have no idea where it is coming from. Just press the rocket, and then run the code a couple of times, and it will clear up.

General scripting in MATLAB#

MATLAB is a scripting language, meaning that any script you write will essentially be put through a command line in order. This means that you must define your variables ahead of time prior to using them, just like any other programming language.

Users can interact with scripts and functions using the input() function, which is setup very similar to the input() function in Python.

Setting up variables and arrays in MATLAB#

MATLAB stands for MATrix LABoratories, so it makes sense that working in matricies are one of the smoothest parts of MATLAB. Instead of importning numpy or pandas or any other library, we can setup matricies and variables very smoothly inside of MATLAB.

% matrix_basics.m
% Demonstrates creating matrices manually and using built-in functions.

% 1. Direct Entry
% Use commas or spaces to separate columns, and a semicolon (;) to separate rows.
A = [1, 2, 3; 4, 5, 6];
disp('--- Matrix A (2x3) ---');
disp(A);

% 2. Creating a Row Vector
% Vectors are 1-D arrays. Spaces or commas work for row vectors.
row_vec = [10 11 12 13];
disp('--- Row Vector ---');
disp(row_vec);

% 3. Creating a Column Vector
% Use semicolons to create a column vector.
col_vec = [20; 21; 22];
disp('--- Column Vector ---');
disp(col_vec);

% 4. Special Matrices using Built-in Functions
% a) Matrix of Zeros (3x2)
B = zeros(3, 2);
disp('--- Matrix B (3x2 Zeros) ---');
disp(B);

% b) Identity Matrix (4x4)
% A square matrix with ones on the main diagonal and zeros elsewhere.
I = eye(4);
disp('--- Identity Matrix (4x4) ---');
disp(I);

% c) Matrix of Random Numbers (2x2)
R = rand(2, 2);
disp('--- Matrix R (2x2 Random) ---');
disp(R);
?2004l


?2004h
?2004l


warning: using the gnuplot graphics toolkit is discouraged

The gnuplot graphics toolkit is not actively maintained and has a number
of limitations that are unlikely to be fixed.  Communication with gnuplot
uses a one-directional pipe and limited information is passed back to the
Octave interpreter so most changes made interactively in the plot window
will not be reflected in the graphics properties managed by Octave.  For
example, if the plot window is closed with a mouse click, Octave will not
be notified and will not update its internal list of open figure windows.
The qt toolkit is recommended instead.
?2004h
?2004l


?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


?2004h
?2004l


--- Matrix A (2x3) ---
?2004h
?2004l


   1   2   3
   4   5   6
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


--- Row Vector ---
?2004h
?2004l


   10   11   12   13
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


--- Column Vector ---
?2004h
?2004l


   20
   21
   22
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


?2004h
?2004l


--- Matrix B (3x2 Zeros) ---
?2004h
?2004l


   0   0
   0   0
   0   0
?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


--- Identity Matrix (4x4) ---
?2004h
?2004l


Diagonal Matrix

   1   0   0   0
   0   1   0   0
   0   0   1   0
   0   0   0   1
?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


?2004h
?2004l


--- Matrix R (2x2 Random) ---
?2004h
?2004l


   0.4954   0.4502
   0.3862   0.3042
?2004h

Once we have general matricies down, we can move on to generating sequences.

% sequence_and_reshape.m
% Demonstrates creating sequences and changing matrix dimensions.

% 1. Creating Sequences (Row Vectors)
% a) Simple sequence: start:end (step size defaults to 1)
seq_a = 1:5; % [1, 2, 3, 4, 5]
disp('--- Sequence A (1:5) ---');
disp(seq_a);

% b) Sequence with a step size: start:step:end
seq_b = 0:0.5:2; % [0, 0.5, 1.0, 1.5, 2.0]
disp('--- Sequence B (0:0.5:2) ---');
disp(seq_b);

% 2. The `linspace` Function
% Creates N evenly spaced points between a start and end value.
lin_vec = linspace(10, 20, 5); % 5 points between 10 and 20
disp('--- linspace (5 points between 10 and 20) ---');
disp(lin_vec);

% 3. Reshaping a Matrix
% First, create a 1x9 vector
one_by_nine = 1:9;

% Then, use `reshape` to turn it into a 3x3 matrix (filling columns first)
C = reshape(one_by_nine, 3, 3);
disp('--- Reshaped Matrix C (3x3) ---');
disp(C);
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


?2004h
?2004l


?2004h
?2004l


--- Sequence A (1:5) ---
?2004h
?2004l


   1   2   3   4   5
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


--- Sequence B (0:0.5:2) ---
?2004h
?2004l


         0    0.5000    1.0000    1.5000    2.0000
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


--- linspace (5 points between 10 and 20) ---
?2004h
?2004l


   10.000   12.500   15.000   17.500   20.000
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


?2004h
?2004l


--- Reshaped Matrix C (3x3) ---
?2004h
?2004l


   1   4   7
   2   5   8
   3   6   9
?2004h

Note that if you make a sequence of seq_a = 1:5, it includes both 1 and 5! No skipping the last value like in Python!

Conditionals in MATLAB#

Conditionals are similar as well. The only difference between python and MATLAB is that MATLAB doesn’t need a colon at the end of the conditional statement, and you must put end at the end of the conditional.

MATLAB also uses elseif instead of elif in Python for else-if statements.

% grade_evaluator.m
% A script to evaluate a score and assign a grade.

% 1. Get user input
score = 95;

% 2. Use conditional statements
if score >= 90
    disp('Grade: A');
elseif score >= 80
    disp('Grade: B');
elseif score >= 70
    disp('Grade: C');
else
    disp('Grade: F');
end

% 3. An additional nested check
if score > 95
    disp('Excellent work! Keep it up.');
end
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

Grade: A
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

?2004h

Looping in MATLAB#

Loops look very similar in MATLAB as they do Python, but MATLAB has a few extra tricks to make the process to smoothly.

For Loops#

For loops are going to iterate through a variable just like in python, but instead of using a range() function or saying that an interable variable is in an array, we can just define the range by going i = [start_value]:[iteration_amount]:[end_value] The start value can be less than the end value as long as the iteration amount is less than 0.

% countdown_timer.m
% A script to demonstrate a basic for loop with a decreasing index.

fprintf('Starting countdown...\n');

% The loop iterates from 5 down to 1, with a step size of -1.
for i = 5:-1:1
    fprintf('%d\n', i);
end

fprintf('Lift off!\n');

% Example of iterating through an array (vector)
number_list = [10, 20, 30, 40];
sum_val = 0;

for num = number_list
    sum_val = sum_val + num;
end

fprintf('The sum of the numbers [10, 20, 30, 40] is: %d\n', sum_val);
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


Starting countdown...
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

5
4
3
2
1
?2004h
?2004l

?2004h
?2004l


Lift off!
?2004h
?2004l

?2004h
?2004l


?2004h
?2004l


?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


The sum of the numbers [10, 20, 30, 40] is: 100
?2004h

While loops#

While loops are nearly identical in MATLAB as they are in Python, just don’t forget your end!

% simple_while_counter.m
% Demonstrates a while loop using only an internal counter.

current_value = 1;
max_value = 5;

fprintf('Starting count...\n');

% The loop continues as long as current_value is less than or equal to max_value.
while current_value <= max_value
    fprintf('Current value is: %d\n', current_value);
    
    % Increment the counter. This is crucial to prevent an infinite loop.
    current_value = current_value + 1; 
end

fprintf('Loop finished.\n');
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


Starting count...
?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l


?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

?2004h
?2004l

Current value is: 1
Current value is: 2
Current value is: 3
Current value is: 4
Current value is: 5
?2004h
?2004l

?2004h
?2004l


Loop finished.
?2004h