MATLAB: Variables, Arrays, Functions, Numerical Methods and Plotting
MATLAB is built around matrices, which makes it powerful for engineering and science calculations. This guide teaches the fundamentals in the order you need them, with short scripts you can run and exercises to practise.
The environment
- Command Window: run commands interactively.
- Workspace: variables currently in memory.
- Editor: write scripts (
.mfiles) and functions. - Live Scripts (
.mlx): combine code, output and formatted text.
Watch the topic explained
Video lesson · about 9 minutes · in production
MATLAB Screen Demonstration
An original lesson that teaches MATLAB with diagrams and a worked example, with captions and a transcript. These are the chapters it will cover; each links to the matching part of this guide.
- 01The MATLAB environment
- 02Vectors, matrices and indexing
- 03Element-wise operations
- 04Scripts and functions
- 05Plotting and a numerical method
Variables, vectors and matrices
a = 5; % scalar (semicolon suppresses output)
v = [1 2 3 4]; % row vector
w = (0:0.1:1)'; % column vector from 0 to 1 in steps of 0.1
A = [2 1; 1 3]; % 2x2 matrix
x = A \ [5; 10]; % solve A*x = b (preferred over inv(A)*b)
Indexing starts at 1: v(2) is 2; A(2,1) is row 2, column 1; v(end) is the last element.
Element-wise versus matrix operations
| Operation | Matrix | Element-wise |
|---|---|---|
| Multiply | A * B (matrix product) |
A .* B (each element) |
| Divide | A / B |
A ./ B |
| Power | A ^ 2 (A*A) |
A .^ 2 (square each element) |
A very common error: t^2 when t is a vector. Use t.^2.
Scripts, functions and control flow
function y = projectile_height(v0, theta_deg, t)
% Height of a projectile (no air resistance)
g = 9.81;
y = v0 * sind(theta_deg) .* t - 0.5 * g * t.^2;
end
Control flow: if/elseif/else, for loops, while loops. Prefer vectorised code over loops where possible: it is shorter and usually faster.
Plotting
t = 0:0.01:3;
y = projectile_height(20, 45, t);
plot(t, y, 'LineWidth', 1.5); grid on
xlabel('Time (s)'); ylabel('Height (m)');
title('Projectile height, v_0 = 20 m/s, \theta = 45°');
Numerical methods
MATLAB includes tools for root finding (fzero), integration (integral, trapz), ordinary differential equations (ode45), optimisation (fminsearch) and curve fitting (polyfit). Understand the method before you rely on the function.
Worked example: when does the projectile land?
Using the function above, we want the positive time when height returns to zero.
f = @(t) projectile_height(20, 45, t);
t_land = fzero(f, [0.1 5])
Result: about 2.88 s. Check by hand: t = 2 v₀ sin θ ÷ g = 2 × 20 × 0.7071 ÷ 9.81 ≈ 2.88 s. ✓ Checking against an analytical result is good practice whenever one exists.
Common mistakes
*instead of.*with vectors ("Incorrect dimensions for matrix multiplication").- Indexing from 0.
- *Using `inv(A)b
** instead ofA\b`. - Variables that shadow functions (naming a variable
sumorplot). - Unlabelled plots and missing units.
- Not commenting code.
Explore learning resources
Worked examples, worksheets and checklists to use alongside this guide. They are learning tools, not answers to an assessment: adapt them to your own task and your institution’s requirements.
ExercisePractice scriptsFive short tasks with self-checks.
- Create a vector of the first 10 square numbers using
.^. (Check: last value 100.) - Solve 3x + 2y = 7, x − y = 1 with
\. (Check: x = 1.8, y = 0.8.) - Plot sin(t) and cos(t) on the same axes for t in [0, 2π], with a legend.
- Write a function that converts Celsius to Fahrenheit for a vector input.
- Use
trapzto integrate x² from 0 to 2 with 1,000 points. (Check: about 2.667.)
ReferenceCommon error messages explainedWhat MATLAB is telling you.
| Message | Likely cause |
|---|---|
| Incorrect dimensions for matrix multiplication | Used * instead of .* |
| Index exceeds the number of array elements | Asked for an element beyond the end |
| Array indices must be positive integers | Index of 0 or a decimal |
| Unrecognized function or variable | Typo, or file not on the path |
| Arrays have incompatible sizes | Adding vectors of different lengths/orientations |
Check your understanding
3 short questions. Choose an answer for each, then check. Every answer comes with an explanation.
Take your learning further
Learn MATLAB with a specialist Academic Expert
Sometimes a concept needs more than a written explanation. A live 1:1 session with an Academic Expert who works in MATLAB lets you ask your own questions, work through examples at your pace and get feedback on your own thinking.
What you can work on together
- Understand vectors, matrices and indexing
- Debug your own scripts and functions
- Vectorise code
- Apply numerical methods correctly
- Produce clear engineering plots
- Prepare for lab tests and projects
How sessions help
- Make sense of your brief and marking criteria, so you know exactly what is being asked.
- Ask the questions you would not ask in a big class, as often as you need.
- Get timely, specific feedback on work you have written yourself.
- Practise explaining your reasoning out loud, ready for vivas, presentations and practicals.
- Extra support with academic English and conventions if English is not your first language.
Teach → coach → review. Experts explain, demonstrate and give feedback. You stay the author of your work and make the decisions in it.
Frequently asked questions
Is there a free alternative to MATLAB?
GNU Octave is largely compatible for basic work, and Python with NumPy is widely used. Many universities provide MATLAB licences to students.
Do I need to learn Simulink?
Only if your course uses it, typically in control, signals and systems modelling.
Our academic integrity commitment
UniLearno supports learning, understanding and independent academic development. Our Academic Experts explain concepts, demonstrate methods, guide research and give feedback on work you have created. We do not complete assessed work, fabricate data or references, or produce anything for you to submit. You remain responsible for your own ideas, analysis, conclusions and final submission, and for following your institution’s academic integrity and AI-use rules.
Why a shortcut costs more than it saves
- It is more visible than it looks. Markers notice when work does not match what they know of you; document history, reference lists and follow-up conversations about your work are all used to check authorship.
- It creates a lasting risk. Services that sell completed assignments have threatened students afterwards, demanding money not to tell their university.
- The gap does not go away. Later units, supervised exams, vivas, placements and the job itself all assume you have the skill.
- Help that teaches is the safer route. Understanding the brief, getting feedback early and practising with an expert closes the gap for good.
Sources and about this guide
- MathWorks. MATLAB documentation and MATLAB Onramp (free online course). mathworks.com.
- Attaway, S. (2022). MATLAB: A practical introduction to programming and problem solving (6th ed.). Butterworth-Heinemann.
- Written by
- UniLearno Learning Team
- Last reviewed
- Found an error?
- Tell us and we will check and correct it.