Fiveable

🫠Intro to Engineering Unit 8 Review

QR code for Intro to Engineering practice questions

8.2 MATLAB programming for engineers

8.2 MATLAB programming for engineers

Written by the Fiveable Content Team • Last updated August 2025
Written by the Fiveable Content Team • Last updated August 2025
🫠Intro to Engineering
Unit & Topic Study Guides

MATLAB Environment and Syntax

MATLAB (Matrix Laboratory) is a high-level programming language and numerical computing environment developed by MathWorks. Engineers use it to perform calculations, analyze data, and create visualizations without needing to manage the low-level details that languages like C require. If your engineering courses involve any serious number-crunching or plotting, MATLAB is likely the tool you'll reach for first.

Core Components and Functionality

When you open MATLAB, you'll see several panels that make up the Integrated Development Environment (IDE):

  • Command Window — where you type and execute commands directly
  • Workspace — shows all the variables you've created and their current values
  • Current Folder — your file browser for navigating to scripts and data files
  • Editor — where you write and save longer programs (scripts and functions)

Basic syntax is straightforward. You assign variables with =, and MATLAB figures out the data type automatically:

</>MATLAB
x = 5          % numeric (double by default)
name = 'Alice' % character array
flag = true    % logical

Arithmetic operators work as you'd expect (+, -, *, /), and comparison operators include == (equal), ~= (not equal), <, and >.

Control structures let you direct program flow. if-else statements handle decisions, for loops repeat a set number of times, and while loops repeat until a condition changes.

One small but important detail: placing a semicolon (;) at the end of a line suppresses output in the Command Window. Without it, MATLAB prints the result of every line, which clutters your screen fast.

Common data types you'll encounter:

  • Numericdouble (default), int8, int32, etc.
  • Logicaltrue / false
  • Character'a', 'hello'
  • Cell arrays — containers that hold mixed types: {1, 'text', [1 2 3]}

Syntax and Documentation

Variable names should be descriptive. MATLAB is case-sensitive, so myVariable and myvariable are different. Most engineers use either camelCase (myVariable) or snake_case (my_variable).

Comments help you (and others) understand your code later:

</>MATLAB
% This is a single-line comment

%{
This is a
multi-line comment
%}

A critical distinction in MATLAB is between matrix operations and element-wise operations. Matrix multiplication uses *, but if you want to multiply corresponding elements of two arrays, you use .*. The same pattern applies to division (./) and exponentiation (.^). Mixing these up is one of the most common beginner errors.

String concatenation uses square brackets: ['Hello ' 'World'] produces 'Hello World'.

MATLAB includes several built-in constants: pi (3.14159...), i and j (imaginary unit), inf (infinity), and NaN (Not a Number, which appears when a calculation is undefined like 0/0).

For help, type help plot in the Command Window for a quick reference, or use doc plot to open the full documentation browser. The documentation is genuinely excellent and includes runnable examples.

Scripting and Functions for Engineering

Script Development and Execution

A script is simply a sequence of MATLAB commands saved in a .m file. Instead of typing commands one at a time in the Command Window, you write them in the Editor, save the file (e.g., myScript.m), and run the whole thing at once.

To run a script, you can:

  1. Click the Run button in the Editor
  2. Type the script's name (without .m) in the Command Window
  3. Press F5 while the script is open in the Editor

Variables created inside a script live in the base workspace, meaning they stick around after the script finishes. This is different from functions, where variables are local and disappear when the function ends.

If you need a variable accessible everywhere, you can declare it with the global keyword, but this is generally discouraged because it makes code harder to debug.

For error handling, MATLAB uses try-catch blocks:

</>MATLAB
try
    result = riskyCalculation(x);
catch ME
    fprintf('Error: %s\n', ME.message);
end

Debugging is straightforward: click the dash next to a line number in the Editor to set a breakpoint. When MATLAB hits that line, execution pauses and you can inspect variables, then step through line by line.

Core Components and Functionality, MATLAB - การตั้งค่าสภาพแวดล้อม

Function Creation and Optimization

Functions are reusable blocks of code with defined inputs and outputs. The basic structure looks like this:

</>MATLAB
function [output1, output2] = myFunction(input1, input2)
    % Function body here
    output1 = input1 + input2;
    output2 = input1 * input2;
end

The file must be saved with the same name as the function (myFunction.m). This is a MATLAB requirement, not just a convention.

You can check how many inputs or outputs the caller provided using nargin and nargout, which is useful for setting default values.

Anonymous functions are handy for short, one-off calculations:

</>MATLAB
f = @(x) x^2 + 2*x + 1;
f(3)  % returns 16

Two key optimization techniques will make your MATLAB code dramatically faster:

  • Vectorization — Replace loops with array operations. Instead of looping through each element to square it, just write x.^2. MATLAB is optimized for array operations, so vectorized code can run 10-100x faster than equivalent loops.
  • Preallocation — If you must use a loop, initialize your output array to its full size before the loop starts (result = zeros(1, 1000)). Without preallocation, MATLAB has to resize the array every iteration, which is very slow.

Matrix and Vector Operations in MATLAB

Matrices are the core data structure in MATLAB. Even a single number is stored internally as a 1×1 matrix. Understanding matrix operations is essential because nearly every MATLAB function is built around them.

Matrix Manipulation and Creation

You can create matrices several ways:

</>MATLAB
A = [1 2; 3 4]       % direct input (2x2 matrix)
B = zeros(3,3)        % 3x3 matrix of zeros
C = ones(2,2)         % 2x2 matrix of ones
I = eye(4)            % 4x4 identity matrix
R = rand(3,3)         % 3x3 matrix of random values between 0 and 1

Indexing uses parentheses with (row, column). A(2,3) grabs the element in the 2nd row, 3rd column. The colon operator extracts submatrices: A(1:3, 2:4) pulls rows 1 through 3 and columns 2 through 4.

To combine matrices, place them side by side for horizontal concatenation ([A B]) or stack them with a semicolon for vertical concatenation ([A; B]). The dimensions need to match along the direction you're joining.

Other useful creation functions include diag([1 2 3]) (creates a diagonal matrix) and linspace(0, 10, 100) (creates 100 evenly spaced points from 0 to 10).

Advanced Matrix Operations

Matrix multiplication follows standard linear algebra rules. For two matrices AA and BB, the number of columns in AA must equal the number of rows in BB:

</>MATLAB
C = A * B    % matrix multiplication

Element-wise operations use the dot prefix and work on corresponding elements:

</>MATLAB
C = A .* B   % multiply element by element
C = A ./ B   % divide element by element
C = A .^ 2   % square each element

Transpose a matrix with the apostrophe: A'. For complex matrices, this gives the conjugate transpose. Use A.' if you want a plain transpose without conjugation.

MATLAB has built-in functions for common linear algebra operations:

  • eig(A) — eigenvalue decomposition
  • svd(A) — singular value decomposition
  • lu(A), qr(A), chol(A) — matrix factorizations (LU, QR, Cholesky)

To solve a system of linear equations Ax=bAx = b, use the backslash operator:

</>MATLAB
x = A \ b

This is more numerically stable and efficient than computing inv(A) * b. The backslash operator automatically selects an appropriate algorithm based on the properties of AA.

Core Components and Functionality, Software tutorial/Getting started - Process Model Formulation and Solution: 3E4

Vector Operations and Multidimensional Arrays

Vectors are just matrices with one dimension equal to 1:

</>MATLAB
row_vec = [1 2 3]      % 1x3 row vector
col_vec = [1; 2; 3]    % 3x1 column vector

Common vector operations:

  • Dot product: dot(v1, v2) or v1 * v2'
  • Cross product: cross(v1, v2) (only for 3D vectors)
  • Normalization (making a unit vector): v / norm(v)

Multidimensional arrays extend beyond 2D. For example, A = rand(3,4,2) creates a 3×4×2 array, which you can think of as two stacked 3×4 matrices. The reshape function rearranges elements: B = reshape(A, [2, 12]) turns that 3×4×2 array into a 2×12 matrix (total element count must stay the same).

Sparse matrices store only the nonzero elements, saving memory when a matrix is mostly zeros. Create them with sparse(row_indices, col_indices, values, m, n). This matters in engineering applications like finite element analysis, where matrices can be enormous but mostly empty.

Data Visualization in MATLAB

Visualization is one of MATLAB's biggest strengths. Being able to plot your results quickly helps you verify calculations, spot errors, and communicate findings.

2D Plotting Techniques

The most basic plot takes two vectors (x values and y values) and draws a line through them:

</>MATLAB
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y)

Other common 2D plot types:

  • scatter(x, y) — discrete data points without connecting lines
  • bar(x, y) — bar graphs for categorical data
  • histogram(data) — shows the distribution of a dataset

To overlay multiple datasets on the same axes, use hold on between plot commands:

</>MATLAB
plot(x, sin(x))
hold on
plot(x, cos(x))
hold off

For data spanning several orders of magnitude, logarithmic scales are useful: semilogx (log x-axis), semilogy (log y-axis), or loglog (both axes). The errorbar function adds uncertainty bars to your plots.

3D Visualization and Customization

For 3D data, you'll typically create a grid of x and y values with meshgrid, compute z values, then plot:

</>MATLAB
[X, Y] = meshgrid(-2:0.1:2, -2:0.1:2);
Z = X.^2 + Y.^2;
surf(X, Y, Z)
  • surf(X, Y, Z) — colored surface plot
  • mesh(X, Y, Z) — wireframe surface
  • contour(X, Y, Z) — 2D level curves (like a topographic map)
  • quiver(X, Y, U, V) — vector field arrows

Customization makes your plots readable and professional:

  • Line styles: '-' (solid), '--' (dashed), ':' (dotted)
  • Markers: 'o' (circle), '*' (asterisk), '+' (plus)
  • 'LineWidth', 2 — thicker lines
  • colormap('hot') — change the color scheme

Always label your axes and add a title:

</>MATLAB
xlabel('Time (s)')
ylabel('Voltage (V)')
title('Circuit Response')
legend('Measured', 'Predicted')

Advanced Visualization and Export

Subplots let you place multiple plots in a grid within one figure. subplot(2,3,4) means a 2-row, 3-column grid, and you're placing the next plot in position 4 (second row, first column).

For animations, capture frames in a loop with getframe and play them with movie. This is useful for visualizing time-dependent simulations.

Image display functions like imshow and imagesc handle image data and matrix visualization. Interactive tools such as data cursors (datatip) let you click on points to read their values.

When you're ready to export figures for reports or presentations:

  • saveas(gcf, 'myplot.png') — quick save in common formats (PNG, PDF, EPS)
  • exportgraphics(gcf, 'myplot.pdf') — produces cleaner, publication-quality output, especially for vector formats like PDF and EPS