Introduction to MATLAB Programming

EE1021 Programming for Engineers - Lecture 12

Basri Erdogan

Introduction to MATLAB

Focus today: quick wins with the command window, tidy variables, fast matrix work.

Python → MATLAB quick wins:

  • 1-based indexing, () for access, end closes blocks.
  • ; suppresses output; ans holds unnamed results.
  • .* / ./ for element-wise; * for matrix mult.
  • Save/load .mat; functions live in their own .m file.

What is MATLAB?

  • Matrix-first numerical environment, ideal for quick prototyping.
  • “Programmable calculator” with built-in visualization.
  • Best when you think in vectors and matrices.
  • Coming from Python: similar numeric goals, but 1-based indexing, column-major order, and end to close blocks.

Why use MATLAB?

  • Polished plotting/UI out of the box (no Matplotlib boilerplate).
  • Toolboxes for control, signal, stats, optimization without extra installs.
  • Tight integration with hardware/Simulink and quick GUIs for lab rigs.
  • IDE/debugger tuned for matrices; live scripts with sliders/inputs.
  • Great for sharing with non-programmers (students, lab mates) who just run scripts.

Command Window: quick math

  • Command window = scratchpad; type expression, press return, see result.
  • Spaces do not matter; use it like a calculator.
  • Try:
2 + 3*5
(10 + 4) / 3
sin(pi/4)

Using Variables

  • Assign and reuse with =; unnamed output goes into ans.
  • End a line with ; to suppress printed output (Python only prints when you call print).
  • Workspace shows live variables; clear with clear (all) or clear name.
r = 5;
area = pi * r^2;   % saved, not printed
area
clear r

Naming rules & built-ins

  • Case-sensitive, start with a letter, use letters/numbers/_ only.
  • Avoid MATLAB keywords; MATLAB will warn you if you clash.
  • Handy built-ins: pi, i/j, inf, nan, eps.
  • Python contrast: no implicit imports—these are always in scope.
radius_cm = 5;                  
area = pi * radius_cm^2;        
machine_tol = eps;              
ok_name = isvarname('user_id'); 
bad_name = isvarname('3cars');

Matrices and Arrays

  • Everything is an array; build them with brackets and colons.
  • Rows separated by semicolons; ranges use start:stop or start:step:stop.
v = [1 2 3 4];        % row vector
M = [1 2; 3 4; 5 6];  % 3x2 matrix
t = 0:0.5:2.5;        % 0 0.5 1.0 1.5 2.0 2.5

Matrices and Arrays (Operations)

  • .* and ./ for element-wise; plain * and / for matrix math.
  • Indexing: A(n) or A(row,col); rows first, then columns.
  • Slices: A(row,:), A(:,col), A(:) to flatten.
  • Python contrast: indices start at 1, use () not [], and element-wise uses .* (NumPy’s default is element-wise).
A = [1 2; 3 4];
B = [10 20; 30 40];
elementwise = A .* B;   % [10 40; 90 160]
matmul = A * B;         % matrix multiply
row2 = A(2, :);         % row slice
lastcol = B(:, end);    % column slice
flat = A(:);            % linearized

Array Subscripting / Indexing

Consider Matrix A:

A = 
1   6   11  16  21
2   7   12  17  22
3   8   13  18  23
4   9   14  19  24
5   10  15  20  25

Examples:

  • A(3,1) → 3
  • A(3) → 3 (Linear indexing)
  • A(1:5,5) → Column 5
  • A(:,5) → Column 5
  • A(21:25) → Elements 21 to 25
  • A(4:5,2:3) → Sub-matrix
  • A([9 14;10 15]) → Indexing with matrix
  • A(:,end) → Last column

The Variable Editor

  • Double-click a variable in the workspace to open the editor.
  • Edit values directly like a spreadsheet; great for quick fixes.
  • who lists current variables from the command line.

The Command History

  • MATLAB stores recent commands; double-click to rerun (watch for changed variables).
  • Use the up-arrow to search through history; start typing to filter.
  • clc clears the command window; history stays.

Functions

  • Learn the built-ins first: mean, std, plot, sum, linspace, etc.
  • Standard pattern:
[out1, out2] = function_name(in1, in2);
  • If you skip the output, it goes into ans.
[m, s] = mean_and_std([1 2 3 4 5]);

Common Functions

  • mean: compute mean
  • std: compute standard deviation
  • min / max: min/max values
  • rand / randn: random numbers
  • size: size of a matrix
  • randperm: random permutation
  • sqrt: square root
  • find: find indices satisfying condition
vals = randn(1,5); 
mu = mean(vals);       % black keyword, magenta vars
sigma = std(vals);
mn = min(vals);
mx = max(vals);
perm = randperm(5,3);
pos_idx = find(vals > 0);
shape = size(vals);

Python parallels: mean/std/min/max ~ numpy.mean/std/min/max; rand/randn ~ np.random.rand/randn; find(cond) ~ np.where(cond); size(A) ~ A.shape.

Data Handling

  • Save workspace: save mysession (creates mysession.mat in current folder).
  • Load later with load mysession; watch for name collisions.
  • Adjust the search path if files live outside the current folder.
  • Python contrast: save/load writes .mat (like pickle/np.save); loading can overwrite variables in the base workspace.
save my_data.mat; 
clear; 
load my_data.mat;

Getting Help

  • help function for quick docs; doc function for full examples.
  • demo shows built-in walkthroughs.
  • MathWorks docs are excellent; community answers are everywhere.
  • If stuck: search the function name + “MATLAB example.”
  • Python parallel: doc func ~ help(func); use which func to see the file being called (like inspect.getfile).
doc plot
help sin

Basics of Programming

Why program in MATLAB?

  • Ubiquitous in engineering labs and courses; matches what industry expects.
  • Hardware/Simulink integration makes control/signal prototypes fast.
  • Live scripts mix narrative, code, and plots for easy sharing.
  • Toolboxes remove dependency wrangling (no pip/conda env drift).
  • Friendly for non-programmers to run and tweak scripts without setup.

MATLAB Data Structures: Strings

  • MATLAB deals with many different types of variable.
  • So far we have only considered single numbers, arrays and matrices.
  • MATLAB can also operate on strings, which are just text variables.
  • Strings are entered using single quotation marks ' ' (double quotes give string scalars; both differ from Python’s list of chars).
  • Strings can be treated much the same as numeric variables.
  • They can be concatenated, but follow standard rules.
  • The functions int2str and num2str convert numbers to strings, for display reasons.
  • The function disp displays a string in the MATLAB command window.

MATLAB Data Structures: Strings (Example)

s1 = 'Hello';
s2 = 'World';
msg = [s1 ' ' s2]; % Concatenation
disp(msg);
num_str = num2str(42);

MATLAB Data Structures: Cells and Structures

Cell Arrays

  • Hold mixed shapes/types in one container using { }.
  • Access elements with { }, then index inside with ().
  • Great for variable-length strings or mixed objects.
  • Think “cell array ≈ Python list (mixed types allowed).”
words = {'foo', 'longer phrase', 'bar'};
words{2}          % returns 'longer phrase'
sizes = [numel(words{1}), numel(words{2})];

Structures

  • Group related data by field name: struct.field.
  • Useful for participant records: names + data together.
  • Fields can hold any type, even nested structs.
  • Think “struct ≈ Python dict with dot access.”
p.name = 'Ali';
p.score = [88 92 90];
p.meta.id = 42;

Creating a script

  • New script: “New script”, Ctrl+N, or File -> New -> Script.
  • Scripts are .m files that run top-to-bottom.
  • Use current folder or add paths so MATLAB can find the file.

Running a script

  • Save then run with Run (F5); highlighted region runs with F9.
  • Scripts share the base workspace (they see current variables).
  • Keep the Current Folder set to where the script lives.

Annotating Code

  • Comment with %; block comments: %{ ... %}.
  • Use %% to split code into runnable cells (Ctrl+Enter).
  • Long lines: end with ... to continue.
%% load data
x = 1:5;  % inline comment

More Advanced Programming

  • Conditionals choose branches; loops repeat work.
  • Always update loop conditions; Ctrl+C stops a runaway loop.
  • Start simple: one if, one for, then expand.
% MATLAB closes blocks with end (Python uses indent/colon)
for i = 1:3
    if i == 2
        disp("middle")
    end
end

Review of MATLAB Operators

Relational

op meaning
== equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
~= not equal to

Logical

op meaning
&& logical and
|| logical or
& element-wise and
| element-wise or

‘If’ Statements

  • Use if to execute code only if a condition is true.
  • Must end with end.
  • Use else or elseif for alternatives.
  • Note: elseif is different from else if (nested).
temp = 32;
if temp > 30
    label = "hot";
elseif temp > 15
    label = "mild";
else
    label = "cold";
end

‘Switch/Case’ Statements

  • Evaluates a single variable against multiple options.
  • Cleaner than many nested elseifs.
  • Often used for string comparisons.
  • Must end with end.
day = "Mon";
switch day
    case {"Sat","Sun"}
        kind = "weekend";
    case {"Mon","Tue","Wed","Thu","Fri"}
        kind = "weekday";
    otherwise
        kind = "unknown";
end

‘For’ Loops

  • Repeat an operation a specific number of times.
  • Loops through values in a vector (e.g., 1:n).
  • Can be nested.
vals = [2 4 6 8];
sum_sq = 0;
doubles = zeros(size(vals));  % preallocate outputs
for i = 1:numel(vals)
    doubles(i) = vals(i)*2;
    sum_sq = sum_sq + vals(i)^2;
end
avg_sq = sum_sq / numel(vals);

‘While’ Loops

  • Repeat until a condition is met.
  • Critical: Update the condition variable inside the loop!
  • Warning: Avoid infinite loops. Use ctrl+c to break.
n = 3;
total = 0;
while n > 0
    total = total + n;
    disp(n)
    n = n - 1;
end
fprintf("Total = %d\n", total);

Writing Functions

% File: summarize_readings.m
function [avg, spread] = summarize_readings(readings)
    if nargin == 0
        error("Need readings input");
    end
    avg = mean(readings);
    spread = std(readings);
end
  • Unlike scripts, functions use their own ‘private’ workspace.
  • Any required input must be passed directly to the function.
  • Only assigned output will be delivered to the (base) workspace.
  • Help information can be entered in comments at the top of the function script.
  • Save the file with the same name as the function (e.g., summarize_readings.m).

Debugging

  • Red underlines = errors; orange = warnings; hover to see hints.
  • Use disp/fprintf to print variables while you iterate.
  • MATLAB suggestions help but are not always correct.

Debugging (Breakpoints)

  • Click the gutter to set a breakpoint (red dot).
  • Code runs to that line; then you can step line-by-line.
  • Inspect variables in the workspace while paused; click again to clear.

Debugging (Visual)