MATLAB Training Notes
MATLAB Training Notes
MATLAB Training Notes
Adding a semicolon to the end of a command will suppress the output, though the command will
still be executed, as you can see in the Workspace.
You can recall previous commands by pressing the Up arrow key on your keyboard.
You can recall previous commands by pressing the Up arrow key on your keyboard.
Clear all variables by using command CLEAR
clc clears command window
pi used for value of pi
abs used for absolute value
eig used for eigenvalues
sin, cos, tan etc.
sqrt
All MATLAB variables are arrays, meaning that each variable can contain multiple elements. A
single number, called a scalar, is actually a 1-by-1 array, meaning it contains 1 row and 1 column.
You can create arrays with multiple elements using square brackets.
>> x = [3 5]
x=
3 5
When you separate numbers by spaces (or commas), MATLAB combines the numbers into a row
vector, which is an array with one row and multiple columns (1-by-n). When you separate them by
semicolons, MATLAB creates a column vector (n-by-1)
You can combine spaces and semicolons to create matrices, which are arrays with multiple rows
and columns. When entering matrices, you must enter them row by row.
>> x = [3 4 5;6 7 8]
x=
3 4 5
6 7 8
In MATLAB, you can perform calculations within the square brackets.
For long vectors, entering individual numbers is not practical. An alternative, shorthand method
for creating evenly spaced vectors is to use the : operator and specify only the start and end
points: first:last.
>> y = 5:8
y=
5 6 7 8
The : operator uses a default spacing of 1, however you can specify your own spacing, as shown
below.
>> x = 20:2:26
x=
20 22 24 26
If you know the number of elements you want in a vector (instead of the spacing between each
element), you could instead use the linspace function: linspace(first,last,number_of_elements). Note
the use of commas (,) to separate inputs to the linspacefunction.
>> x = linspace(0,1,5)
x=
0 0.250 0.500 0.750 1.000
Both linspace and the : operator create row vectors. However, you can convert a row vector into a
column vector using the transpose operator ('). This can be done in reverse as well.
>> x = 1:3;
>> x = x'
x=
1
2
3
You can create column vectors in a single command by creating the row vector and transposing it
all on one line. Note the use of parentheses here to specify the order of operations.
>> x = (1:2:5)'
x=
1
3
5
You can also use ; after each unit in vector i.e. [9; 10; 11]
You can also denotate a row in a matricx by using semi colon
o i.e [1 2 3; 4 5 6; 7 8 9]
to specify an item in a vector: use name of vector(x) *which unit you want to know the value of; can do
range using :
can also get all values using : i.e. x(:)
MATLAB contains many functions that help you to create commonly used matrices, such as
matrices of random numbers.
>> x = rand(2)
x=
0.8147 0.1270
0.9058 0.9134
Note that the 2 in the command rand(2) specifies that the output will be a 2-by-2 matrix of random
numbers.
Can also do this and determine matrix dimensions; i.e. x=rand(2,3) is a 2x3 matrix of
random numbers
Function zeros creates a matrix of all zeros (can use dimensions as above as well)
You can save variables in your workspace to a MATLAB specific file format called a MAT-file
using the savecommand.
>> save foo x
The command above saves a variable named x to a MAT-file named foo.mat.
You can load variables from a MAT-file using the loadcommand.
>> load foo
To upload data, right click -- import data
You can extract values from an array using row, column indexing.
>> x = A(5,7);
This syntax extracts the value in the 5th row and 7th column of A and assigns the result to the
variable x.
You can use the MATLAB keyword end as either a row or column index to reference the last
element.
>> x = A(end,2);
Note that you can use arithmetic with the keyword end. For example:
>> x = A(end-1,end-2)
When used as an index, the colon operator (:) specifies all the elements in that dimension. The
syntax
>> x = A(2,:)
creates a row vector containing all of the elements from the second row of A.
The colon operator can refer to a range of values. The following syntax creates a matrix
containing the first, second, and third rows of the matrix A.
>> x = A(1:3,:)
A single index value can be used to reference vector elements. For example
>> x = v(3)
returns the third element of vector v when v is either a row or column vector.
A single range of index values can be used to reference a subset of vector elements. For
example
>> x = v(3:end)
returns a subset of vector v containing the elements from 3 to the end.
Can change using these methods too….. i.e data(1,3) = 0.5
You can delete a row or column in a matrix by assigning empty set of square brackets to
that row/column. Ie. A(4,:) = []
To get the inverse of a matrix use inv(a)
MATLAB is designed to work naturally with arrays. For example, you can add a scalar value to all
the elements of an array.
>> y = x + 2
You can add together any two arrays of the same size.
>> z = x + y
You can multiply or divide all of the elements of an array by a scalar.
>> z = 2*x
>> y = x/3
Basic statistical functions in MATLAB can be applied to a vector to produce a single output. The
maximum value of a vector can be determined using the max function.
>> xMax = max(x)
MATLAB has functions that perform mathematical operations on an entire vector or array of
values in a single command.
>> xSqrt = sqrt(x)
Round = rounded average
The * operator performs matrix multiplication. So, if you use * to multiply two equally sized
vectors, since the inner dimensions do not agree, you will get an error message.
In contrast, the .* operator performs elementwise multiplication and allows you to multiply the
corresponding elements of two equally sized arrays.
The size function can be applied to an array to produce a single output variable containing the
array size.
>> s = size(x)
The size function can be applied to a matrix to produce either a single output variable or two
output variables. Use square brackets ([ ]) to obtain more than one output.
>> [xrow,xcol] = size(x)
The maximum value of a vector and its corresponding index value can be determined using
the max function. The first output from the max function is the maximum value of the input
vector. When called with two outputs, the second output is the index value.
>> [xMax,idx] = max(x)
Documentation =. Help button
You can enter
>> doc fcnName
to get information on any MATLAB function.
Two vectors of the same length can be plotted against each other using the plot function.
>> plot(x,y)
The plot function accepts an additional argument that allows you to specify the color, line style,
and marker style using different symbols in single quotes.
>> plot(x,y,'r--o')
The command above plots a red (r) dashed (--) line with a circle (o) as a marker. You can learn
more about the symbols available in the documentation for Line Specification.
Notice that the first plot you created no longer exists. To plot one line on top of another, use
the hold on command to hold the previous plot while you add another line. You can also use
the hold off command to return to the default behavior.
Use close all command to close all open figure windows
The plot function accepts optional additional inputs consisting of a property name and an
associated value.
>> plot(y,'LineWidth',5)
The command above plots a heavy line (width 5). You can learn more about available properties
in the documentation for Lineseries Properties.
Labels can be added to plots using plot annotation functions, such as title. The input to these
functions is a string. Strings in MATLAB are enclosed in single quotes ( ').
>> title('Plot Title')
Use the ylabel function to add the label
Create live script – saves code
Relational operators, such as >, <, ==, and ~= perform comparisons between two values. The
outcome of a comparison for equality or inequality is either 1 (true) or 0 (false). – can also assign
this to variables
You can compare a vector or matrix to a single scalar value using relational operators. The result
is a logical array of the same size as the original array.
[5 10 15] > 12
ans =
0 0 1
Corresponding elements of two arrays can be compared using relational operators. The two
arrays must be the same size and the result is a logical array of the same size.
MATLAB contains logical operators which combine multiple logical conditions such as AND (&)
and OR (|). The &operator returns true (1) if both elements are true, and false (0) otherwise. For
example:
>> x = (pi > 5) & (0 < 6)
x=
0
You can use a logical array as an array index, in which case MATLAB extracts the array elements
where the index is true. The following example will extract all elements in v1that are greater than
six.
>> v = v1(v1 > 6)
v=
6.6678
9.0698
You can use logical indexing to reassign values in an array. For example, if you wish to replace
all values in the array xthat are equal to 999 with the value 0, use the following syntax.
x(x==999) = 0
At times, you may want to execute a section of code only if a certain condition is met. You can do
this using an ifstatement. Each if statement must contain one ifkeyword and one end keyword,
and code between the ifand end keywords is executed only when the condition is met.
x = rand;
if x > 0.5
y = 3; %Executed only if x > 0.5
end
Can introduce else in between the if and end with next line else, next line command
A common programming task is to execute a section of code repeatedly. In MATLAB, you can do
this with a for loop.
for i = 1:3
disp(i)
end
When this code is run, the code between the for and endkeywords will be executed three times
in this case, as the loop counter (i) progresses from 1:3 (1, 2, and 3).
Who command displays all the variable names you have used
Whos displays more about the variables – currently in memory, types of each, memory allocated to each,
whether they are complex or not
By default, MATLAB displays numbers with four decimal place values.
This is known as short format.
However, if you want more precision, you need to use
the format command.
The format long command displays 16 digits after decimal.
The format short e command allows displaying in exponential form with
four decimal places plus the exponent.
The format bank command rounds numbers to two decimal places.
The format long e command allows displaying in exponential form with
four decimal places plus the exponent.
The format rat command gives the closest rational expression resulting
from a calculation.
Edit to edit a file, or create one (in editor)
o To see the result of this code…. Type in simply name of file in editor… or click
run at top in editor
You can also create a matrix r by appending these two vectors, the
vector r2, will be the second row of the matrix −
r = [r1;r2]
However, to do this, both the vectors should have same number of
elements.
Similarly, you can append two column vectors c1 and c2 with n and m
number of elements. To create a column vector c of n plus m
elements, by appending these vectors, you write −
c = [c1; c2]
You can also create a matrix c by appending these two vectors; the
vector c2 will be the second column of the matrix −
c = [c1, c2]
MATLAB will execute the above statement and return the following
result −
my_string = Tutorials Point
whos
MATLAB will execute the above statement and return the following
result −
Name Size Bytes Class Attributes
my_string 1x16 32 char
Operator Purpose
\ Left-division operator.
/ Right-division operator.
= Assignment operator.
Name Meaning
Inf Infinity.
Command Purpose
Command Purpose
Command Purpose
%s Format as a string.
%d Format as an integer.
The format function has the following forms used for numeric display −
Command Purpose
Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following
table shows some of the commonly used commands for plotting −
Command Purpose
1 <
Less than
2
<=
3 >
Greater than
4
>=
5 ==
Equal to
6
~=
Not equal to
Sr.No Statement & Description
.
2 if...else...end statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
4 nested if statements
You can use one if or elseif statement inside
another if or elseifstatement(s).
5 switch statement
A switch statement allows a variable to be tested for equality against a
list of values.
1 while loop
3 nested loops
You can use one or more loops inside any another loop.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
Colon notation
A(:,j) is the jth column of A.
A(:,:) is the equivalent two-dimensional array. For matrices this is the same
as A.
A(:) is all the elements of A, regarded as a single column. On the left side
of an assignment statement, A(:) fills A, preserving its shape from
before. In this case, the right side must contain the same number of
elements as A.
Function Purpose
IMPORTING DATA
Sr.No. Function & Description
1 A = importdata(filename)
2
A = importdata('-pastespecial')
Loads data from the system clipboard rather than from a file.
3 A = importdata(___, delimiterIn)
4
A = importdata(___, delimiterIn, headerlinesIn)
Loads data from ASCII file, filename, or the clipboard, reading numeric
data starting from line headerlinesIn+1.
Returns the detected delimiter character for the input ASCII file
in delimiterOut and the detected number of header lines
in headerlinesOut, using any of the input arguments in the previous
syntaxes.
Data export
Data export (or output) in MATLAB means to write into files. MATLAB allows
you to use your data in another application that reads ASCII files. For this,
MATLAB provides several data export options.
Diary (or log) file of keystrokes and the resulting text output.
MEX-file to access your C/C++ or Fortran routine that writes to a particular text
file format.
There are two ways to export a numeric array as a delimited ASCII data file
−
Using the dlmwrite function