MATLAB Programming Techniques Quick Reference
MATLAB Programming Techniques Quick Reference
1. Introduction
2. Structuring Data
Summary: Overview of MATLAB Data Types
Each array type is intended to store data with a characteristic organization. Some arrays hold data all
of the same data type, and others allow storage of different data types.
Homogeneous Arrays
Homogeneous arrays are scalars, vectors, matrices, and higher dimensional arrays whose elements
all have the same data type. Elements of an array can be numbers, logical values, dates and times,
strings, or one of many other other data types. For instance, a logical matrix would be a rectangular
array with elements that are all logical values.
Unless otherwise specified MATLAB stores all numeric variables as type double .
char Text
string
Heterogeneous Arrays
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 1/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Sometimes data are not all the same data type or size. There are specific containers for these
heterogeneous data.
The primary difference between a character array and a string array is that an individual
element of a character array is a character and an element of a string array is a piece of text,
which consists of several characters.
t1 = table(var1,var2, 'VariableNames',{'Thought1','OnSecondThought'})
t1 =
When several variables in your workspace hold data about the 2x2 table
same observations, you can use the table function to collect this Thought1 OnSecondThought
information into a table. ________ _______________
"Ford" 32.7
"Toyota" 1
t2 = t1(2,"Thought1");
t2 =
You can index into a table using array indexing with
table
parentheses. Columns can be specified either numerically or by
Thought1
name.
________
"Toyota"
car = {'Ford','Expedition';32.7,true}
car =
Create a cell array using curly
braces and separating elements 2×2 cell array
with commas and semicolons.
{'Ford' } {'Expedition'}
{[32.7000]} {[ 1]}
car(1,1)
You can index into a cell array
using standard MATLAB indexing ans =
with parentheses, (). This returns 1x1 cell array
a portion of the original cell array. {'Ford'}
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 2/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
car{1,1}
You can access the contents of
cells in a cell array by indexing ans =
with curly braces, {}, rather than 'Ford'
parentheses, ().
car.make = "Ford"
This syntax creates a structure named
car with a field named make and car = struct with fields:
assigns a value to that field. make: "Ford"
car.model = "Expedition"
The same dot notation can be used to car = struct with fields:
create new fields. make: "Ford"
model: "Expedition"
car(2).model = "Prius"
[] "Prius"
car(2).model
You can use the field name and array
ans =
indexing to extract the data.
"Prius"
Concatenating Horizontally
Regardless of where the comma-separated list comes from, square brackets concatenate the data
into a row vector.
Cell Arrays
x
x =
The 2-by-2 cell array stored in the x variable contains four scalars.
[10] [20]
[30] [40]
[x{:}]
Using square brackets creates a numeric row vector. The elements
ans =
of x are concatenated columnwise.
10 30 20 40
Structure Arrays
data.coords
ans =
0.2081 0.1663 0.5292
ans =
The structure array stored in the data variable has four elements.
0.0265 0.6137 0.8135
data.coords returns the coords field of each element separately.
ans =
0.6473 0.7456 0.4188
ans =
0.9763 0.9831 0.0538
y = [data.coords]
y =
Columns 1 through 4
Concatenating with square brackets concatenates columnwise, 0.2081 0.1663 0.5292 0.0265
which creates a single 1-by-12 vector from the four 1-by-3 vectors. Columns 5 through 8
0.6137 0.8135 0.6473 0.7456
Columns 9 through 12
0.4188 0.9763 0.9831 0.0538
...
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 3/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Concatenating Vertically
You can use the vertcat function on comma-separated lists to concatenate vertically.
Cell Arrays
x
x =
The 2-by-2 cell array stored in the x variable contains four scalars.
[10] [20]
[30] [40]
vertcat(x{:})
ans =
10
Extract multiple outputs from x and concatenate vertically.
30
20
40
Structure Arrays
data.coords
ans =
0.2081 0.1663 0.5292
ans =
The structure array stored in the data variable has four
0.0265 0.6137 0.8135
elements.
ans =
0.6473 0.7456 0.4188
ans =
0.9763 0.9831 0.0538
x = vertcat(data.coords)
x =
0.2081 0.1663 0.5292
Stack the data vertically
0.0265 0.6137 0.8135
0.6473 0.7456 0.4188
0.9763 0.9831 0.0538
y
y =
y is a 3-element structure with fields name and price 1x3 struct array with fields:
name
price
y.name
ans = 'Banana'
The name fields contains the name of fruits.
ans = 'Apple'
ans = 'Orange'
{y.name}
Those names can be put into cells and concatenated into a cell
ans =
array using curly braces.
{'Banana'} {'Apple'} {'Orange'}
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 4/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
These are called anonymous functions. Again, you use the @ symbol. Specify inputs with
parentheses.
h = @sin;
Construct a function handle with an @ sign.
h(0)
ans =
Call the function handle in the same way that you would call the 0
function directly. h(pi/2)
ans =
1
integral(h,0,pi)
ans =
2.0000
Some functions, such as integral , require an input function. In
this case, pass a function handle as an input. integral(@log,1,2)
ans =
0.3863
You can apply a function to each element of an array with arrayfun . The arrayfun function works
on any array.
>> B = arrayfun(func,A)
Outputs Inputs
B An array whose elements are the output func A function handle
of func operating on each element of
A An array
A.
If func returns scalars of the same data type, then B is an array of that data type. If the outputs of
func are non-scalar or non-uniform, set the "UniformOutput" property to false . In this case, B is
a cell array.
B = arrayfun(func,A,"UniformOutput",false)
You can apply a function to the contents of each element of a cell array with cellfun .
>> B = cellfun(func,C)
Outputs Inputs
B An array whose elements are the output func A function handle
of func operating on each element of
C A cell array
C.
Use the "UniformOutput" property to specify that the output of func is either not a scalar or non-
uniform.
B = cellfun(func,C,"UniformOutput",false)
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 5/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
The varfun and rowfun functions allow you to apply a function to columns or rows of a table,
respectively. They have very similar syntax.
>> B = rowfun(func,tbl)
Outputs Inputs
B A table or timetable where the ith row is func A function to apply to rows of the table.
equal to func(A{i,:}) . tbl A table or timetable.
>> B = varfun(func,tbl)
Outputs Inputs
B A table or timetable containing the calculations func A function to apply to columns of the table.
on the specified columns.
tbl A table or timetable.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 6/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
MATLAB provides conversion functions of the form typeA2typeB to convert Extracting Multiple Elements
between datatypes. from Cell and Structure Arrays
Function Handles
The table below summarizes most of the functions available in MATLAB to convert between data
types.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 7/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Product or brand names of cars are trademarks or registered trademarks of their respective holders.
A table requires minimal overhead for each variable and for storing table properties.
A structure requires 64 bytes of overhead for each field name and 112 bytes for each container. If a structure array has more
than one element, each element will require additional overhead. So the total memory used is
In the example below, you can see how to calculate the total memory of a cell array of character
vectors
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 8/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
vectors.
Preallocation
You can use the functions zeros and ones to preallocate numeric arrays.
x = zeros(1,50000);
By default, zeros and ones create an array having the datatype
double .
x = zeros(1,50000,'single');
You can create an array having other datatypes by specifying an
y = zeros(1,50000,'int16');
additional input.
x(8) = 3;
Another way to preallocate an array is to assign a value to the last x =
element of the array. 0 0 0 0 0 0 0 3
You can also preallocate non-numeric data types, such as cell arrays and structure arrays.
Think of these arrays as consisting of the containers (cells and structures) and the contents (any
datatype and size).
Preallocating a cell array or a structure array assigns space for the containers themselves, not the
contents. This means that preallocation of the container variables is most beneficial when the
container array itself is large, regardless of the size of the contents of the individual containers.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 9/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
C = cell(1,4);
To preallocate a structure array, start by defining the last element of the array. MATLAB will
automatically replicate the field names to all of the preceding elements in the array.
S(5) = struct('field1',6,'field2',7)
To measure the execution time of MATLAB code, you can use the tic and toc functions.
tic
Start timer
x = rand(1000);
Run code
toc
Stop timer, report results
Elapsed time is 1.206429 seconds.
To improve the performance of your code, you should first understand what parts of it take the most
time. The MATLAB Profiler analyzes where your code spends the most time.
Vectorized code is more concise and faster than the non-vectorized solutions.
nonVectorized.mlx vectorized.mlx
1. % Generate data 1. % Generate data
2. r = rand(1,5000); 2. r = rand(1,5000);
3. 3.
4. % Compute the difference between 4. % Compute the difference between
5. % the adjacent elements 5. % the adjacent elements
6. d = zeros(1,4999); 6. d = diff(r);
7. for i=1:4999
8. d(i) = r(i+1)-r(i);
9. end
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 10/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Scripts and functions that call each other often need to share data. Passing inputs to functions is one
way functions can share data.
...
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 11/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
In some cases, you can leave inputs in their original type. For example, many mathematical
operations will work on any numeric type. MATLAB also performs some conversions as needed. For
example, numeric variables can be used in logical contexts, in which case they are automatically
converted to logical (with zero becoming false and all non-zero becoming true).
In other cases, you can use conversion functions to force any allowed input type into the desired type.
Dates Datetime, numeric array (representing components, such as day, month, year),
text
Dates datetime
Note that these functions all leave the inputs unchanged if they are already in the desired type.
That is, if t is a datetime variable, t = datetime(t); will have no effect.
Only the text data types were converted to strings. The variable b is type double .
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 12/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Querying Inputs
MATLAB includes numerous functions that test a particular attribute of a variable and return a logical
result. These function names typically start with the word is .
Function Returns
Function Returns
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 13/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Use multiple wrapper functions that use the same underlying algorithm. Each wrapper function can
present a different interface to users for different applications.
Most users can use interface2 . Advanced users can use advancedInterface (or call
the algorithm directly).
To check if all the inputs were provided in the function call, you can use the function nargin . When
called within the function body, nargin returns the number of inputs that were passed when the
function was called.
Number of input
nargin
arguments
To allow the users to specify certain inputs (but not others), use an empty array [] .
In the function body - check if the input is empty using the function isempty . If it is empty, assign
a default value.
In the function call - use an empty array [] instead of the input value.
You can map multiple input arguments (e.g. a set of name-value pairs) to a single input variable
varargin in the function definition.
Use validatestring to ensure that any user input is exactly as you expect (including type and
capitalization), without overly constraining your user. If the input text does not unambiguously match
any of the valid strings, validatestring generates an error.
str = validatestring("distribution",["DistanceMetric","DistributionName","NumSamples"])
str =
"DistributionName"
str = validatestring("dist",["DistanceMetric","DistributionName","NumSamples"])
str = validatestring("Algorithm",["DistanceMetric","DistributionName","NumSamples"])
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 14/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Similar to how you handle a variable number of inputs, you can use nargout to determine how many
outputs were requested when a function was called. You can use varargout to represent any
number of output arguments.
Private Functions
To prevent your application's internal functions from being accessible outside the application, you can
place them in a folder named private .
Local Functions
To create local functions, place them below the primary function in the same code file.
findShapes.mlx
1. function findShapes %Primary function
2. ...
3. end
4.
5. function detectCircle %Local function
6. ...
7. end
8.
9. function detectSquare %Local function
10. ...
11. end
You can use the warning and error functions to generate custom warnings and errors.
Error Warning
error("MyProject:invalidValue",... warning("MyProject:ValueOutOfRange",...
"The value must be numeric."); "The value must be between 1 and 10.")
The value must be numeric. The value was expected to be between 1 and 10.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 15/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
The try/catch construct attempts to run the code within the try block. If an error condition occurs, then
the execution is interrupted and switched immediately into the catch block.
try
% Attempt code
catch mexc
% Backup case – something went wrong
% An MException object called mexc now exists
end
A test script is a MATLAB script that checks that the outputs of MATLAB files are as you expect. To
create a test script, use the assert function to create tests and separate the tests into sections.
Code sections allow you to compile multiple tests into a single file. The section header describes the
test.
Each section of a test script maintains its own workspace. Thus, in each section, you must define all
needed variables.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 16/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
function testName1(testCase)
The local functions:
% code for test 1
contain the tests
end
have names that start or end with the case-insensitive word
"test"
function testName2(testCase)
have a single input, here testCase
% code for test 2
end
Many simple function-based unit tests will not use the input to the
local functions, but it should always be included. Tests that verify
behavior (e.g. warnings or errors) or allow for shared variables
between tests use this input explicitly.
You run the test function the same way you run a test script.
result = runtests("mainFunctionNameTest");
Verification Functions
There are many qualification functions available in the function-based testing framework.
verifyClass verifyNotEmpty
verifyEmpty verifyNotEqual
verifyEqual verifyNotSameHandle
verifyError verifyNumElements
verifyFail verifyReturnsTrue
verifyFalse verifySameHandle
verifyGreaterThan verifySize
verifyGreaterThanOrEqual verifySubstring
verifyInstanceOf verifyThat
verifyLength verifyTrue
verifyLessThan verifyWarning
verifyLessThanOrEqual verifyWarningFree
verifyMatches
The local test functions have a single input, named testcase in the example below. Your test code
should use it as the first input to the verification function.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 17/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
You can add pre- and post-test tasks to your testing function by adding functions with the special
names setupOnce and teardownOnce which have the same signature as the other test functions.
function setupOnce(testCase)
In this example, the test code and the application code are in % save the name of the application folder you will add
separate locations. You will use the application folder in the % to the TestData structure
teardown function. So, rather than redefining it, you can save it in testCase.TestData.appDir = ...
the testCase variable to the TestData property. This property is a fullfile("C:","class","work","ApplicationDirectory");
structure variable to which you can add fields as you desire. Any
fields that are added to this variable are accessible by all functions % add the application folder to the path for testing
in the test function file. addpath(testCase.TestData.appDir)
end
function teardownOnce(testCase)
Now, remove the directory from the path in the teardownOnce
function. See that the variable you previously defined, appDir , is % removes the added path
accessible through testCase.TestData . Note that the structure rmpath(testCase.TestData.appDir)
TestData is named automatically, whereas you can name the
function input, testCase in this example, whatever you want. end
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 18/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
For some warnings, the Code Analyzer can help you automatically fix the code.
Mousing over the orange dash or the highlighted portion of the code shows you the code analyzer warning.
For easy fixes, like a missing semicolon, you have the option to fix the issue.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 19/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
When the Code Analyzer does not provide an automatic fix, you can either fix the warning yourself, or
suppress it.
Other issues flagged by the code analyzer do not have a simple fix.
A comment is added to the end of the line, and the warning is removed.
It is a good idea to add further comments to explain why you've suppressed the message.
Suppressing warnings can be a helpful way to demonstrate that the issue has been considered. This
means developers in the future won't spend time worrying about a nonexistent problem with the code.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 20/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
Note that, before making a fix to your code, you should always stop your debugging session first so
that you can save your changes.
If you want to enter debug mode immediately when an uncaught error is generated, you can enable
the Pause on Errors option.
To run a folder report on the current folder, access the Reports menu from the Current Folder Actions
menu.
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 21/22
9/24/21, 9:25 PM MATLAB Programming Techniques - Quick Reference
MATLAB Projects
MATLAB Projects help manage code spread across multiple files. They are also using for sharing
code with others.
Source Control
Source control enables you to keep track of and manage previous versions of your project.
10. Conclusion
https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlpr&language=en&release=R2021a 22/22