Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views22 pages

MATLAB Training Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 22

 The equals sign (=) in MATLAB is the assignment operator

 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

Notice that the for loop contains a single end keyword, similar to if statements.

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

 If you have two row vectors r1 and r2 with n and m number of


elements, to create a row vector r of n plus m elements, by appending
these vectors, you write −
 r = [r1,r2]

 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]

 However, to do this, both the vectors should have same number of


elements.
 To multiply vectors…. Use . (i.e. v=[1,2,3,4]; v2=v.^2;)
 Creating a character string is quite simple in MATLAB. In fact, we have
used it many times. For example, you type the following in the
command prompt −

 my_string = 'Tutorials Point'

 MATLAB will execute the above statement and return the following
result −
 my_string = Tutorials Point

 MATLAB considers all variables as arrays, and strings are considered


as character arrays. Let us use the whos command to check the
variable created above −

 whos

 MATLAB will execute the above statement and return the following
result −
 Name Size Bytes Class Attributes
 my_string 1x16 32 char

 Interestingly, you can use numeric conversion functions


like uint8 or uint16to convert the characters in the string to their
numeric codes. The charfunction converts the integer vector back to
characters −

Common syntax in MATLAB

Operator Purpose

+ Plus; addition operator.

- Minus; subtraction operator.

* Scalar and matrix multiplication operator.

.* Array multiplication operator.

^ Scalar and matrix exponentiation operator.

.^ Array exponentiation operator.

\ Left-division operator.

/ Right-division operator.

.\ Array left-division operator.

./ Array right-division operator.

: Colon; generates regularly spaced elements and represents


an entire row or column.

() Parentheses; encloses function arguments and array indices;


overrides precedence.

[] Brackets; enclosures array elements.


. Decimal point.

… Ellipsis; line-continuation operator

, Comma; separates statements and elements in a row

; Semicolon; separates columns and suppresses display.

% Percent sign; designates a comment and specifies formatting.

_ Quote sign and transpose operator.

._ Nonconjugated transpose operator.

= Assignment operator.

Special Variables and constants

Name Meaning

ans Most recent answer.

eps Accuracy of floating-point precision.

i,j The imaginary unit √-1.

Inf Infinity.

NaN Undefined numerical result (not a number).


pi The number π

Commands for Managing a Session


MATLAB provides various commands for managing a session. The following
table provides all such commands −

Command Purpose

clc Clears command window.

clear Removes variables from memory.

exist Checks for existence of file or variable.

global Declares variables to be global.

help Searches for a help topic.

lookfor Searches help entries for a keyword.

quit Stops MATLAB.

who Lists current variables.

whos Lists current variables (long display).

Commands for Working with the System


MATLAB provides various useful commands for working with the system,
like saving the current work in the workspace as a file and loading the file
later.

It also provides various commands for other system-related activities like,


displaying date, listing files in the directory, displaying current directory,
etc.

The following table displays some commonly used system-related


commands −

Command Purpose

cd Changes current directory.

date Displays current date.

delete Deletes a file.

diary Switches on/off diary file recording.

dir Lists all files in current directory.

load Loads workspace variables from a file.

path Displays search path.

pwd Displays current directory.

save Saves workspace variables in a file.

type Displays contents of a file.

what Lists all MATLAB files in the current directory.


wklread Reads .wk1 spreadsheet file.

Input and Output Commands


MATLAB provides the following input and output related commands −

Command Purpose

disp Displays contents of an array or string.

fscanf Read formatted data from a file.

format Controls screen-display format.

fprintf Performs formatted writes to screen or file.

input Displays prompts and waits for input.

; Suppresses screen printing.

The fscanf and fprintf commands behave like C scanf and printf functions.


They support the following format codes −

Format Code Purpose

%s Format as a string.

%d Format as an integer.

%f Format as a floating point value.


%e Format as a floating point value in scientific notation.

%g Format in the most compact form: %f or %e.

\n Insert a new line in the output string.

\t Insert a tab in the output string.

The format function has the following forms used for numeric display −

Format Function Display up to

format short Four decimal digits (default).

format long 16 decimal digits.

format short e Five digits plus exponent.

format long e 16 digits plus exponents.

format bank Two decimal digits.

format + Positive, negative, or zero.

format rat Rational approximation.

format compact Suppresses some line feeds.

format loose Resets to less compact display mode.


Vector, Matrix and Array Commands
The following table shows various commands used for working with arrays,
matrices and vectors −

Command Purpose

cat Concatenates arrays.

find Finds indices of nonzero elements.

length Computes number of elements.

linspace Creates regularly spaced vector.

logspace Creates logarithmically spaced vector.

max Returns largest element.

min Returns smallest element.

prod Product of each column.

reshape Changes size.

size Computes array size.

sort Sorts each column.

sum Sums each column.


eye  Creates an identity matrix.

ones Creates an array of ones.

zeros Creates an array of zeros.

cross Computes matrix cross products.

dot Computes matrix dot products.

Det Computes determinant of an array.

magic Creates a magic array (sum of every row/column/diagonal


are same)

inv Computes inverse of a matrix.

pinv Computes pseudoinverse of a matrix.

rank Computes rank of a matrix.

rref Computes reduced row echelon form.

cell Creates cell array.

celldisp Displays cell array.

cellplot Displays graphical representation of cell array.


num2cell Converts numeric array to cell array.

deal Matches input and output lists.

iscell Identifies cell array.

Plotting Commands
MATLAB provides numerous commands for plotting graphs. The following
table shows some of the commonly used commands for plotting −

Command Purpose

axis Sets axis limits.

fplot Intelligent plotting of functions.

grid Displays gridlines.

plot Generates xy plot.

print Prints plot or saves plot to a file.

title Puts text at top of plot.

xlabel Adds text label to x-axis.

ylabel Adds text label to y-axis.

axes Creates axes objects.


close Closes the current plot.

close all Closes all plots.

figure Opens a new figure window.

gtext Enables label placement by mouse.

hold Freezes current plot.

legend Legend placement by mouse.

refresh Redraws current figure window.

set Specifies properties of objects such as axes.

subplot Creates plots in subwindows.

text  Places string in figure.

bar Creates bar chart.

loglog Creates log-log plot.

polar Creates polar plot.

semilogx Creates semilog plot. (logarithmic abscissa).

semilogy Creates semilog plot. (logarithmic ordinate).

stairs Creates stairs plot.


stem Creates stem plot.

Sr.No. Operator & Description

1 <

Less than

2
<=

Less than or equal to

3 >

Greater than

4
>=

Greater than or equal to

5 ==

Equal to

6
~=

Not equal to
Sr.No Statement & Description
.

1 if ... end statement

An if ... end statement consists of a boolean expression followed by


one or more statements.

2 if...else...end statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.

3 If... elseif...elseif...else...end statements


An if statement can be followed by one (or more) optional elseif...and
an else statement, which is very useful to test various conditions.

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.

6 nested switch statements


You can use one switch statement inside another switchstatement(s).

Sr.No Loop Type & Description


.

1 while loop

Repeats a statement or group of statements while a given condition is


true. It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.

3 nested loops
You can use one or more loops inside any another loop.

Sr.No Control Statement & Description


.

1 break statement

Terminates the loop statement and transfers execution to the statement


immediately following the loop.

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(i,:) is the ith row of A.

A(:,:) is the equivalent two-dimensional array. For matrices this is the same
as A.

A(j:k) is A(j), A(j+1),...,A(k).


A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k).

A(:,:,k) is the kth page of three-dimensional array A.

A(i,j,k,: is a vector in four-dimensional array A. The vector includes A(i,j,k,1),


) A(i,j,k,2), A(i,j,k,3), and so on.

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 

double Converts to double precision number

single Converts to single precision number

int8 Converts to 8-bit signed integer

int16 Converts to 16-bit signed integer

int32 Converts to 32-bit signed integer

int64 Converts to 64-bit signed integer

uint8 Converts to 8-bit unsigned integer


uint16 Converts to 16-bit unsigned integer

uint32 Converts to 32-bit unsigned integer

uint64 Converts to 64-bit unsigned integer

IMPORTING DATA
Sr.No. Function & Description

1 A = importdata(filename)

Loads data into array A from the file denoted by filename.

2
A = importdata('-pastespecial')

Loads data from the system clipboard rather than from a file.

3 A = importdata(___, delimiterIn)

Interprets delimiterIn as the column separator in ASCII file, filename, or


the clipboard data. You can use delimiterIn with any of the input
arguments in the above syntaxes.

4
A = importdata(___, delimiterIn, headerlinesIn)

Loads data from ASCII file, filename, or the clipboard, reading numeric
data starting from line headerlinesIn+1.

5 [A, delimiterOut, headerlinesOut] = importdata(___)

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.

You can create the following type of files −

 Rectangular, delimited ASCII data file from an array.

 Diary (or log) file of keystrokes and the resulting text output.

 Specialized ASCII file using low-level functions such as fprintf.

 MEX-file to access your C/C++ or Fortran routine that writes to a particular text
file format.

Apart from this, you can also export data to spreadsheets.

There are two ways to export a numeric array as a delimited ASCII data file

 Using the save function and specifying the -ascii qualifier

 Using the dlmwrite function

Syntax for using the save function is −


save my_data.out num_array -ascii

where, my_data.out is the delimited ASCII data file created, num_array is a


numeric array and  −ascii is the specifier.

Syntax for using the dlmwrite function is −


dlmwrite('my_data.out', num_array, 'dlm_char')

where, my_data.out is the delimited ASCII data file created, num_array is a


numeric array and  dlm_char is the delimiter character.

You might also like