MATLAB mainly works with numeric matrices, but it supports multiple data types:
| Data Type | Description |
|---|---|
| double | Default numeric type |
| single | Single precision floating point |
| int8/int16/int32/int64 | Signed integers |
| uint8/uint16/… | Unsigned integers |
| logical | Boolean true/false |
| char | Character arrays |
| string | Modern string datatype |
| cell | Container for mixed data types |
| struct | Data structure with named fields |
Example:
a = 10; % double
b = int16(5); % integer
c = true; % logical
d = "Engine"; % string
Automotive Example:
Vehicle sensor data such as engine speed or wheel speed is typically stored as numeric arrays (double or single) for processing.
MATLAB stands for Matrix Laboratory, meaning all variables are essentially matrices.
| Type | Example |
|---|---|
| Scalar (1×1) | a = 5; |
| Vector (1×n or n×1) | v = [1 2 3 4]; |
| Matrix (m×n) | A = [1 2 3; 4 5 6]; |
Examples:
a = 5; % Scalar
v = [1 2 3 4]; % Row vector
A = [1 2 3;
4 5 6]; % Matrix
Automotive Example:
A lookup table for engine torque vs RPM is typically stored as a matrix.
MATLAB supports two types of operations:
| Operation Type | Operator |
|---|---|
| Matrix operation | * |
| Element-wise operations | .*, ./, .^ |
Example:
A = [1 2; 3 4];
B = [5 6; 7 8];
A * B % matrix multiplication
A .* B % element-wise multiplication
Automotive Example:
Multiplying sensor gain calibration values element-wise with raw sensor data.
MATLAB uses 1-based indexing, meaning indexing starts from 1 instead of 0.
| Expression | Description |
|---|---|
| A(1,2) | Access element at row 1, column 2 |
| A(:,1) | Select entire first column |
| A(2,:) | Select entire second row |
Example:
A = [10 20 30;
40 50 60];
A(1,2) % returns 20
A(:,1) % entire first column
A(2,:) % entire second row
Automotive Example:
Extracting wheel speed sensor values from a sensor data array.
In MATLAB, scripts and functions are used differently based on scope and reusability:
| Script | Function |
|---|---|
| Executes in base workspace | Has its own workspace |
| No input/output arguments | Has inputs and outputs |
| Used for quick analysis | Used for reusable code |
Script example:
a = 5;
b = 10;
c = a + b;
Function example:
function c = add(a,b)
c = a + b;
end
Automotive Example:
Functions are used for signal filtering or torque calculations in automotive applications.
Logical operators are used to perform logical comparisons and return true or false values.
| Operator | Meaning |
|---|---|
| & | AND |
| | | OR |
| ~ | NOT |
Example:
speed = 80;
if speed > 60
disp('Overspeed')
end
Automotive Example:
Check if vehicle speed exceeds a threshold and brake condition is active.
MATLAB provides two main types of loops for repeated execution of code:
| Loop Type | Description |
|---|---|
| for loop | Executes a fixed number of times |
| while loop | Executes while a condition is true |
Examples:
% for loop
for i = 1:5
disp(i)
end
% while loop
while speed < 100
speed = speed + 10;
end
Automotive Example:
Iterating over logged vehicle data samples for analysis or processing.
Vectorization is the process of replacing loops with matrix or array operations to improve performance.
| Approach | Code |
|---|---|
| Loop version | for i=1:100 y(i)=x(i)*2; end |
| Vectorized version | y = x * 2; |
Benefits:
- Faster execution
- Better memory usage
Automotive Example:
Processing CAN signal arrays quickly using vectorized operations.
Cell arrays are used to store different types of data in a single variable.
| Feature | Description |
|---|---|
| Heterogeneous data | Can store numbers, text, logical values, etc. |
| Curly braces { } | Used for creating and accessing elements |
Example:
C = {10, 'Engine', true};
C{1} % Access first element
Automotive Example:
Storing mixed vehicle parameters like parameter names, values, and status flags.
Structures are used to store related data in the form of named fields.
| Feature | Description |
|---|---|
| Named fields | Access data using field names |
| Flexible | Can store different data types in fields |
| Dot notation | Used to access values (e.g., struct.field) |
Example:
vehicle.speed = 80;
vehicle.rpm = 3000;
vehicle.gear = 4;
Automotive Example:
Vehicle signal bus data is often organized and stored using structures.
These functions are used to determine the dimensions and number of elements in arrays:
| Function | Description |
|---|---|
| length | Returns the largest dimension of the array |
| size | Returns the dimensions of the matrix |
| numel | Returns the total number of elements |
Example:
A = [1 2 3; 4 5 6];
length(A)
size(A)
numel(A)
Automotive Example:
Used for checking signal buffer sizes in vehicle data processing systems.
Anonymous functions are inline functions defined without creating a separate file.
| Feature | Description |
|---|---|
| Inline definition | Defined in a single line |
| No file required | Does not need a separate function file |
| Function handle | Stored using @ symbol |
Example:
f = @(x) x^2 + 2*x;
Automotive Example:
Used for quick mathematical models during algorithm development.
Plotting in MATLAB is used to visualize data graphically, such as trends, signals, and relationships between variables.
| Function | Purpose |
|---|---|
| plot() | Create 2D line plots |
| xlabel() | Label x-axis |
| ylabel() | Label y-axis |
Example:
plot(time, speed)
xlabel('Time')
ylabel('Vehicle Speed')
Automotive Example:
Plotting vehicle speed vs time during test runs for performance analysis.
Preallocation is the process of allocating memory for arrays before using them, which improves performance.
| Approach | Code |
|---|---|
| Without preallocation (Bad) | for i=1:1000 A(i)=i; end |
| With preallocation (Good) | A = zeros(1,1000); |
Example:
% Bad practice
for i = 1:1000
A(i) = i;
end
% Good practice
A = zeros(1,1000);
Automotive Example:
Useful when handling large vehicle log datasets efficiently.
The workspace in MATLAB is the area where variables are stored and managed during program execution.
| Type | Description |
|---|---|
| Base workspace | Main workspace for scripts and command window |
| Function workspace | Local workspace inside functions |
Example:
a = 10;
b = 20;
c = a + b; % Variables stored in workspace
Automotive Example:
Simulink signals are often exported to the workspace for analysis and visualization.
Debugging in MATLAB is the process of identifying and fixing errors in code using built-in tools.
| Tool | Description |
|---|---|
| Breakpoints | Pause execution at a specific line |
| Step execution | Execute code line-by-line |
| dbstop | Automatically stop execution on errors |
Example:
dbstop if error
Automotive Example:
Debugging vehicle control algorithms to ensure correct behavior and safety.
MATLAB toolboxes are add-on packages that extend MATLAB’s capabilities for specific applications.
| Toolbox | Usage |
|---|---|
| Control System Toolbox | Design and analysis of control systems |
| Signal Processing Toolbox | Analyze and process signals |
| Vehicle Network Toolbox | Work with CAN, LIN, and automotive networks |
Example:
% Example: Using control toolbox (PID tuning concept)
% pidTuner(sys)
Automotive Example:
Control System Toolbox is commonly used for PID tuning in vehicle control systems.
A handle class in MATLAB is used in object-oriented programming where objects are passed by reference instead of by value.
| Feature | Description |
|---|---|
| Reference behavior | Changes affect all references to the object |
| Efficient memory use | No copying of object data |
| Used in OOP | Helpful for complex system modeling |
Example:
classdef Engine < handle
end
Automotive Example:
Used for simulation objects in system modeling such as engine or vehicle models.
MATLAB provides functions to read data from files such as CSV, Excel, and text files.
| Function | Usage |
|---|---|
| readtable() | Read data into a table format |
| readmatrix() | Read numeric data as a matrix |
| fopen()/fscanf() | Read text files manually |
Example:
data = readtable('vehicle_data.csv');
Automotive Example:
Reading vehicle log files from CAN or ECU tests for analysis.
The MATLAB path defines the directories where MATLAB searches for functions, scripts, and files.
| Command | Purpose |
|---|---|
| addpath(‘folder’) | Add a folder to MATLAB path |
| savepath | Save the current path for future sessions |
Example:
addpath('my_functions')
savepath
Automotive Example:
Organizing large Model-Based Design (MBD) projects with multiple function libraries.
Relational operators are used to compare values and return logical (true or false) results.
| Operator | Meaning |
|---|---|
| == | Equal to |
| ~= | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
Example:
speed = 80;
speed > 60
Automotive Example:
Checking if vehicle speed exceeds the cruise control threshold.
The clear command removes variables from the MATLAB workspace.
| Command | Description |
|---|---|
| clear | Removes all variables from workspace |
| clear speed | Removes specific variable |
| clear all | Removes variables, functions, and MEX links |
Example:
clear
clear speed
clear all
Automotive Example:
Resetting the workspace before running vehicle data analysis scripts.
The functions disp() and fprintf() are used to display output in MATLAB, but they differ in formatting capabilities.
| Function | Purpose |
|---|---|
| disp() | Displays simple output without formatting |
| fprintf() | Displays formatted output with control over text and variables |
Example:
disp('Engine Speed')
fprintf('RPM = %d\n', rpm)
Automotive Example:
Printing diagnostic messages during algorithm testing.
The colon operator is used to generate sequences of numbers in MATLAB.
| Usage | Description |
|---|---|
| 1:10 | Generates numbers from 1 to 10 |
| 0:0.1:1 | Generates numbers with a step size of 0.1 |
Example:
a = 1:10;
b = 0:0.1:1;
Automotive Example:
Creating time vectors for simulation signals in vehicle models.
The linspace function creates a vector of linearly spaced values between two specified points.
| Syntax | Description |
|---|---|
| linspace(start, end, n) | Generates n equally spaced points between start and end |
Example:
t = linspace(0, 10, 100);
Automotive Example:
Generating simulation time samples for vehicle system analysis.
Concatenation in MATLAB is the process of combining matrices or arrays either horizontally or vertically.
| Type | Example |
|---|---|
| Horizontal | A = [1 2]; B = [3 4]; C = [A B]; |
| Vertical | C = [A; B]; |
Example:
A = [1 2];
B = [3 4];
C = [A B]; % Horizontal concatenation
C = [A; B]; % Vertical concatenation
Automotive Example:
Combining multiple sensor datasets into a single matrix for analysis.
MATLAB provides many built-in mathematical functions for performing common calculations.
| Function | Description |
|---|---|
| sin() | Sine function |
| cos() | Cosine function |
| sqrt() | Square root |
| log() | Natural logarithm |
Example:
sqrt(25)
Automotive Example:
Used in calculating vehicle acceleration models and other engineering computations.
The find() function returns the indices of non-zero or true elements in an array.
| Usage | Description |
|---|---|
| find(condition) | Returns indices where condition is true |
Example:
A = [10 20 30 40];
find(A > 25)
Automotive Example:
Finding events where vehicle speed exceeds a defined limit.
The isempty() function checks whether an array is empty.
| Function | Description |
|---|---|
| isempty(A) | Returns true if A is empty, otherwise false |
Example:
isempty(A)
Automotive Example:
Checking if a sensor data buffer is empty before processing.
The isnan() function detects NaN (Not-a-Number) values in an array.
| Function | Description |
|---|---|
| isnan(data) | Returns true for elements that are NaN |
Example:
isnan(data)
Automotive Example:
Handling invalid sensor readings by detecting NaN values in vehicle data.
The length() function returns the largest dimension of an array.
| Function | Description |
|---|---|
| length(A) | Returns the size of the largest dimension of A |
Example:
length([1 2 3 4])
Automotive Example:
Checking the number of samples in a vehicle signal.
The reshape() function changes the dimensions of a matrix without altering its elements.
| Function | Description |
|---|---|
| reshape(A, m, n) | Reshapes array A into m-by-n matrix |
Example:
A = 1:6;
reshape(A, 2, 3)
Automotive Example:
Reshaping sensor data buffers for efficient processing and analysis.
The transpose operation flips a matrix over its diagonal, switching rows and columns.
| Method | Description |
|---|---|
| A’ | Transpose of matrix A |
| transpose(A) | Function form of transpose |
Example:
A = [1 2 3];
A' % Transpose using operator
transpose(A) % Transpose using function
Automotive Example:
Changing orientation of signal vectors for processing and analysis.
The sum() function calculates the total of elements in an array or matrix.
| Usage | Description |
|---|---|
| sum(A) | Sum of all elements (vector) or column-wise (matrix) |
| sum(A,1) | Sum of each column |
| sum(A,2) | Sum of each row |
Example:
sum([1 2 3])
sum(A,1)
Automotive Example:
Used in calculating total energy consumption in vehicle systems.
The mean() function calculates the average value of elements in an array.
| Function | Description |
|---|---|
| mean(A) | Returns the average of elements in A |
Example:
mean([10 20 30])
Automotive Example:
Calculating average vehicle speed or battery voltage over time.
The max() and min() functions are used to find the maximum and minimum values in an array.
| Function | Description |
|---|---|
| max(A) | Returns the largest value in A |
| min(A) | Returns the smallest value in A |
Example:
max(A)
min(A)
Automotive Example:
Finding maximum engine temperature or minimum battery voltage during operation.
The sort() function arranges elements of an array in ascending or descending order.
| Function | Description |
|---|---|
| sort(A) | Sorts elements of A in ascending order |
| sort(A,’descend’) | Sorts elements in descending order |
Example:
sort([5 2 8 1])
Automotive Example:
Sorting test data samples for analysis and validation.
The unique() function returns the unique elements from an array by removing duplicates.
| Function | Description |
|---|---|
| unique(A) | Returns unique elements of array A |
Example:
unique([1 2 2 3 3])
Automotive Example:
Removing duplicate CAN message IDs from vehicle communication data.
The tic and toc functions are used to measure execution time of code.
| Function | Description |
|---|---|
| tic | Starts the timer |
| toc | Stops the timer and displays elapsed time |
Example:
tic
pause(1)
toc
Automotive Example:
Used for optimizing signal processing algorithms in vehicle systems.
The zeros() function creates an array or matrix filled with zeros.
| Function | Description |
|---|---|
| zeros(m,n) | Creates an m-by-n matrix of zeros |
Example:
zeros(3,3)
Automotive Example:
Initializing signal buffers before processing vehicle data.
The ones() function creates an array or matrix filled with ones.
| Function | Description |
|---|---|
| ones(m,n) | Creates an m-by-n matrix of ones |
Example:
ones(2,2)
Automotive Example:
Initializing control parameters in vehicle systems.
The rand() function generates random numbers between 0 and 1.
| Function | Description |
|---|---|
| rand(m,n) | Generates an m-by-n matrix of random numbers |
Example:
rand(3,3)
Automotive Example:
Used for noise simulation in sensor testing and validation.
The eye() function creates an identity matrix, where diagonal elements are 1 and others are 0.
| Function | Description |
|---|---|
| eye(n) | Creates an n-by-n identity matrix |
Example:
eye(3)
Automotive Example:
Used in control system matrices such as state-space models.
The diag() function creates a diagonal matrix or extracts diagonal elements from a matrix.
| Function | Description |
|---|---|
| diag(v) | Creates a diagonal matrix from vector v |
| diag(A) | Extracts diagonal elements of matrix A |
Example:
diag([1 2 3])
Automotive Example:
Used in state-space control modeling for system representation.
The clc command clears the MATLAB command window.
| Command | Description |
|---|---|
| clc | Clears all text from the command window |
Example:
clc
Automotive Example:
Cleaning output before running vehicle test scripts for clear results.
The who and whos commands are used to display variables in the MATLAB workspace.
| Command | Description |
|---|---|
| who | Lists variable names in the workspace |
| whos | Displays detailed information about variables |
Example:
who
whos
Automotive Example:
Checking variables during vehicle data analysis and debugging.
The path command displays the directories where MATLAB searches for files and functions.
| Command | Description |
|---|---|
| path | Displays the current MATLAB search path |
Example:
path
Automotive Example:
Managing large automotive toolchains with multiple directories and libraries.
The save() function is used to store variables from the workspace into a file.
| Function | Description |
|---|---|
| save filename | Saves all workspace variables to a .mat file |
| save filename var | Saves specific variable |
Example:
save data.mat
Automotive Example:
Saving vehicle test datasets for further analysis and reporting.
The load() function is used to load variables from a .mat file into the workspace.
| Function | Description |
|---|---|
| load filename | Loads all variables from a .mat file |
| load filename var | Loads specific variable |
Example:
load data.mat
Automotive Example:
Loading recorded ECU data for analysis and validation.
The help command displays documentation and usage information for MATLAB functions.
| Command | Description |
|---|---|
| help function_name | Displays help for a specific function |
Example:
help plot
Automotive Example:
Used as a quick reference during automotive algorithm development.