Matlab Introduction
ME 322 Lab 2
Fall 2026
Alexander Gardner
Where lecture is, and what today adds
Lecture has covered (through p.25)
Today's lab gives you the tools
- Significant figures, accuracy vs precision
- Array addressing - reach into data
- Error definitions: true, relative, approximate
- Flowcharts and pseudocode - plan before you code
- Round-off and truncation error
- if / elseif / else - make a decision
- Taylor series approximation
- for and while - repeat something
- Binary and floating-point storage
- Logical operators - combine conditions
- Mantissa, base, exponent
Why this order matters
Coming next in lecture
Machine epsilon, condition number.
Lecture just showed you that a computer stores only finitely
many digits. Today you build the loop that MEASURES that
limit.
Array addressing - “slicing”
The colon alone means “all elements of this component”. When in between numbers, it represents an inclusive range
Vectors
Matrices: A(rows, columns)
V(:)
A(:,3)
every element
V(2:5)
elements 2 through 5
V(end)
last element
V([1 3 5])
just those three
all rows, column 3
A(2,:)
row 2, all columns
A(:,2:5)
all rows, columns 2-5
A(2:3,1:3)
rows 2-3, columns 1-3
A(:)
every element, stacked into one column
Rows first, then columns. Getting that backwards is the most common indexing bug.
Array addressing
How to obtain C from matrix B with
Matlab Commands?
C(2:3,1:3)
ANSWER
Basic functions
Basic functions
Example
Create A:
What will min(A) return?
What will size(A) return?
What will numel(A) return?
What will length(A) return?
Special matrix
Structured programming
Every numerical method in this course is built from just three control structures.
1. Sequence
2. Selection
3. Repetition
Do one thing, then the next.
Statements run top to bottom.
Choose between paths.
if / elseif / else
Do it again.
for and while loops
a = 2;
b = a + 3;
c = b*2;
if x >= 0
y = sqrt(x);
else
y = 0;
end
for k = 1:5
disp(k)
end
That is the whole toolkit. Bisection, Newton-Raphson, Gauss elimination - all of it is these three, combined.
Programming design
Flowchart:
-
a visual or graphical representation of an algorithm
Uses a series of blocks and arrows, each of which
represents an operation or step in the algorithm
Pseudocode:
-
Use code-like statements in place of the graphical
symbols in flowcharts
Keywords such as IF, DO, INPUT, etc are capitalized
Conditions, processing steps, and tasks are in
lowercase and indented
Flowchart
Conditional statements
Execute code blocks based on conditions
if/end: 1 condition → 1 action
if/else/end: 1 condition → 2 action
Example 1:
Calculate y=√x only if x is positive. Show
the flowchart and pseudocode.
Conditional statements
if/elseif/else/end: 2+
conditions
Conditional statements
Matlab syntax and relational operators
Example 1:
if x>=0
y=sqrt(x)
end
Problem 1
Calculate the letter grade given the following number grade G range using
flowchart, pseudocode, and matlab:
To output a word, called string in code, use quotes "" around the word
Display a word: disp("word")
A
G ≥ 80
B
70 ≤ G < 80
C
60 ≤ G < 70
F
G < 60
Logical operators
Logical operators - work these out
A comparison returns 1 (true) or 0 (false). Predict each answer before running it.
Try these
A = 3;
The operators
z = A < 3
A = 3; B = 4;
z = (A < 3 &
A = 3; B = 4;
z = (A < 3 |
B == 4)
B == 4)
&
AND - both must be true
|
OR - at least one true
~
NOT - flips it
==
equal to (two signs!)
~=
not equal to
= assigns a value. == compares two.
Mixing them up is a classic first-month bug.
Loops: for and while
Pick between the two based on one question: do you know how many times, something must run before you
start it?
for - a known number of times
while - until a condition fails
for k = 5:2:11
x = k + 1
end
n = 10;
while n > 5
n = n - 1
end
k takes 5, 7, 9, 11 - four passes.
start : step : stop
Runs until n > 5 stops being true.
Use it when the count is fixed:
"do this for all 21 time steps".
Use it when the count depends on the
answer: "iterate until the error < tol".
Make sure something inside changes the
condition, or it never stops.
Example 2
Approximate the integral of the function f(x) = 2x + 3 over the interval [1,10] using
the midpoint rule with 4 rectangles using a FOR loop.
Midpoint rule: Approximates the definite integral
by dividing the interval
[a,b] into n equal subintervals and summing the areas of the rectangles whose
height are evaluated at the midpoint of each subinterval.
Matlab procedure
1)
Collect known info and identify what we need to solve for
From the problem:
solve for:
Sum of all area rectangles
1)
Define variables
a)
2)
Initialize (preallocate memory)
a)
3)
A
Solve
a)
b)
4)
a,b,n,w
Compute area of each rectangle using for loop and store areas in A
Sum of all areas
Output
a)
Display total area
Calculations:
Example 3
Approximate e^x with taylor series sum_{k=0}^∞ x^k/k! until the next term is < tol.
• Hint: Update term multiplicatively to avoid factorial; emulate do–while via while true/break.
x=3
tol = 1e-3
sum_ = 1; term = 1; k = 0;
while true
k = k + 1;
term = term * (x / k);
if abs(term) < tol
break
end
sum_ = sum_ + term;
end
approx = sum_
Problem 2 - counting with a loop
Given the vector
v = [3
-4
0
Start here
-3
1]
count how many entries are positive, how many are negative, and
how many are zero.
Print all three counts.
Requirements
- Use a for loop over the elements.
- Use if / elseif / else inside the loop.
- Initialise your three counters before the loop starts.
- Comment why each counter starts at zero.
v = [3 -4 0 -3 1];
pos = 0;
neg = 0;
zer = 0;
for i = 1:numel(v)
x = v(i);
% your if/elseif here
end
pos
neg
zer
numel(v) gives the number of elements.
Problem 3 - while loop with a tolerance
Newton's law of cooling
Start here
A cup of coffee starts at 68 C in a 21 C room.
Each minute its temperature updates by
T = 68;
Ta = 21;
k = 0.019;
dt = 1;
minutes = 0;
T = T - k*(T - Ta)*dt
with k = 0.019 /min, Ta = 21, dt = 1 min.
How many minutes until the coffee drops below 60 C?
Use a while loop - you do not know the count in advance, which is
exactly when while beats for.
while T > 60
% update T
% count the minute
end
minutes
This is HW1 problem 3 in disguise you will meet it again tonight.
Bringing it together: machine epsilon
This is the flowchart on page 28 of your lecture notes - the next thing Prof. Ganatos will cover.
The idea
The loop
A computer stores a finite number of digits. So there is a
smallest number you can add to 1 and still get something
different from 1.
em = 1;
while (1 + em) > 1
em = em/2;
end
em = 2*em;
% undo the last halving
That number is machine epsilon.
The algorithm: start at 1, keep halving while 1 + e is still
bigger than 1. When it stops being bigger, you have gone one
step too far - double back.
fprintf('%g\n', em)
Check it against MATLAB's built-in:
eps
Both give 2.2204e-16.
A while loop is right here because you cannot know in advance how many halvings it takes - that is the whole
point.
Wrap-up - and HW1 goes out today
Today
HW1 - due Thursday 09/24, 11:59 PM
- A(row, column) - the colon means "all".
On Brightspace now. Three problems:
- Flowchart and pseudocode before you write code.
- Parachutist by hand, Euler with dt = 2 s out to t = 8 s, then
the error against the exact answer.
- if / elseif / else to choose a path.
- & and | to combine conditions. == compares, = assigns.
- Second-order drag: derive the closed form, then redo it
numerically.
- for when you know the count, while when you don't.
- Newton's law of cooling in MATLAB.
Submitted code is graded on the 10-point rubric: 4
correct, 3 method comment, 2 line comments, 1 AI
disclosure.
Next week: functions and root finding.