Matlab_Introduction_by_Michael_Medvinsky.ppt

khaliq1 7 views 25 slides Oct 13, 2024
Slide 1
Slide 1 of 25
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25

About This Presentation

MATLAB INTRO


Slide Content

11
MATLAB PRIMERMATLAB PRIMER
by Michael Medvinsky(2014)by Michael Medvinsky(2014)

MATLABMATLAB
MATLAB is a program for doing numerical computation. MATLAB is a program for doing numerical computation.
It was originally designed for solving linear algebra type It was originally designed for solving linear algebra type
problems using matrices. Itproblems using matrices. It’’s name is derived from s name is derived from
MATrix LABoratory.MATrix LABoratory.
MATLAB has since been expanded and now has built-in MATLAB has since been expanded and now has built-in
functions for solving problems requiring data analysis, functions for solving problems requiring data analysis,
signal processing, optimization, and several other types signal processing, optimization, and several other types
of scientific computations. It also contains functions for of scientific computations. It also contains functions for
2-D and 3-D graphics and animation. 2-D and 3-D graphics and animation.

MATLABMATLAB
When you first open MATLAB, notice:When you first open MATLAB, notice:
1.1.The The command window command window is where you'll give is where you'll give
MATLAB its input and view its output. MATLAB its input and view its output.
2.2.The The workspaceworkspace shows you all of your current shows you all of your current
working variables and other objects. working variables and other objects.
3.3.The The historyhistory shows you all commands you used shows you all commands you used
in CW.in CW.
4.4.The The Editor Editor for MATLAB scripts (M-files) . To for MATLAB scripts (M-files) . To
save & run the m-file type 'F5'. To open the save & run the m-file type 'F5'. To open the
editor with a new or old m-file use the command editor with a new or old m-file use the command
openopen file_namefile_name

MATLAB helpMATLAB help
For help, command description etc use F1 or following For help, command description etc use F1 or following
commands:commands:

helphelp command_name command_name

helpwinhelpwin command_name command_name

docdoc command_name command_name

helpdeskhelpdesk command_name command_name

demo demo command_name command_name

lookfor lookfor keywordkeyword (search unknown command) (search unknown command)
http://www.mathworks.com/support/http://www.mathworks.com/support/
For example when running For example when running ““help sinhelp sin”” one get one get
SIN Sine of argument in radians.
SIN(X) is the sine of the elements of X.
See also ASIN, SIND.
Overloaded functions
Reference page in Help browser doc sin

Some Useful commandsSome Useful commands
whatwhat List all m-files in current directoryList all m-files in current directory
dir/lsdir/ls List all files in current directoryList all files in current directory
type testtype test Display test.m in command windowDisplay test.m in command window
delete testdelete test Delete test.mDelete test.m
cd/chdircd/chdir Change directoryChange directory
pwdpwd Show current directoryShow current directory
which testwhich test Display directory path to Display directory path to ‘‘closestclosest’’ test.m test.m
whowho List known variablesList known variables
whoswhos List known variables plus their sizeList known variables plus their size
clearclear Clear variables from workspaceClear variables from workspace
clcclc Clear the command windowClear the command window

MATLAB & MatricesMATLAB & Matrices
MATLAB treats all variables as matrices. For our MATLAB treats all variables as matrices. For our
purposes a matrix can be thought of as an array, in fact, purposes a matrix can be thought of as an array, in fact,
that is how it is stored. that is how it is stored.
Vectors are special forms of matrices and contain only Vectors are special forms of matrices and contain only
one row OR one column.one row OR one column.
Scalars are matrices with only one row AND one columnScalars are matrices with only one row AND one column

Variable NamesVariable Names
Variable names Variable names AREARE case sensitive case sensitive
Variable names can contain up to 63 characters (as of MATLAB 6.5 Variable names can contain up to 63 characters (as of MATLAB 6.5
and newer). One can use and newer). One can use namelengthmaxnamelengthmax command to command to
verify it.verify it.
Variable names must start with a letter followed by letters, digits, Variable names must start with a letter followed by letters, digits,
and underscores.and underscores.
MATLAB variables are defined by assignment. There is no need to MATLAB variables are defined by assignment. There is no need to
declare in advance the variables that we want to use or their type. declare in advance the variables that we want to use or their type.
ExampleExample
x=1;x=1; % Define the scalar variable x% Define the scalar variable x
y=[1 2 3]y=[1 2 3] % row vector % row vector
z=[1;2;3]z=[1;2;3] % column vector% column vector
A=[1 2 3;4 5 6;7 8 9] A=[1 2 3;4 5 6;7 8 9] % 3x3 matrix % 3x3 matrix
whos whos % List of the variables defined% List of the variables defined
Note: terminate statement with semicolon (;) to suppress output.Note: terminate statement with semicolon (;) to suppress output.

Special VariablesSpecial Variables
ansans Default variable name for resultsDefault variable name for results
pipi Value of Value of ππ
epseps Smallest incremental numberSmallest incremental number
infinf InfinityInfinity
NaNNaN Not a numberNot a number e.g. 0/0e.g. 0/0
i,j,1i,1j i,j,1i,1j imaginary unit imaginary unit i, i, i.e.i.e. square root of -1 square root of -1
realminrealminThe smallest usable positive realnumberThe smallest usable positive realnumber
realmaxrealmaxThe largest usable positive real numberThe largest usable positive real number
SpecialVars.mSpecialVars.m

Other symbolsOther symbols
>>>> promptprompt
. . .. . . continue statement on next linecontinue statement on next line
,, separate statements and dataseparate statements and data
%% start comment which ends at end of linestart comment which ends at end of line
;; (1)(1)suppress outputsuppress output
(2)(2)used as a row separator in a matrixused as a row separator in a matrix
:: specify range specify range

Relational OperatorsRelational Operators
MATLAB supports six relational operators. MATLAB supports six relational operators.
Less ThanLess Than <<
Less Than or EqualLess Than or Equal <=<=
Greater ThanGreater Than >>
Greater Than or EqualGreater Than or Equal >=>=
Equal ToEqual To ====
Not Equal ToNot Equal To ~=~=

Math & Assignment OperatorsMath & Assignment Operators
PowerPower ^^oror.^.^a^ba^boror a.^ba.^b
MultiplicationMultiplication * * oror.*.*a*ba*borora.*ba.*b
DivisionDivision //oror././a/ba/borora./ba./b
oror \\oror.\.\b\ab\aororb.\ab.\a
NOTE: NOTE: 56/8 = 8\5656/8 = 8\56
-- (unary) (unary) ++ (unary) (unary)
AdditionAddition ++ a + ba + b
SubtractionSubtraction - - a - ba - b
AssignmentAssignment == a = ba = b (assign (assign bb to to aa))
Operators.mOperators.m

MATLAB Logical OperatorsMATLAB Logical Operators
MATLAB supports five logical operators.MATLAB supports five logical operators.
not/~not/~element wise/scalar logical NOTelement wise/scalar logical NOT
and/&and/&element wise logical ANDelement wise logical AND
oror/ |/ |element wise logical ORelement wise logical OR
&&&& logicallogical (short-circuit) AND(short-circuit) AND
|||| logicallogical (short-circuit) AND(short-circuit) AND

Logical FunctionsLogical Functions
MATLAB also supports some logical functions.MATLAB also supports some logical functions.

xorxor (a, b) exclusive or (a, b) exclusive or

anyany(x) returns 1 if any element of x is nonzero(x) returns 1 if any element of x is nonzero

allall(x) (x) returns 1 if all elements of x are returns 1 if all elements of x are
nonzerononzero

isnanisnan(x) returns 1 at each NaN in x(x) returns 1 at each NaN in x

isinfisinf(x) returns 1 at each infinity in x(x) returns 1 at each infinity in x

finitefinite(x) returns 1 at each finite value in x(x) returns 1 at each finite value in x

findfind(x) (x) find indices and values of non zero elementsfind indices and values of non zero elements

Some Matrix functionsSome Matrix functions
zeroszeros(rows, cols) – create zero matrix(rows, cols) – create zero matrix
randrand(rows, cols) – generate random matrix(rows, cols) – generate random matrix
onesones(rows, cols) – matrix with 1 in all entries(rows, cols) – matrix with 1 in all entries
eyeeye (rows, cols) – identity matrix (rows, cols) – identity matrix
sub2indsub2ind, , ind2subind2sub indices manipulation indices manipulation

Extracting a Sub-MatrixExtracting a Sub-Matrix
A portion of a matrix can be extracted and stored in a A portion of a matrix can be extracted and stored in a
smaller matrix by specifying the names of both matrices smaller matrix by specifying the names of both matrices
and the rows and columns to extract. The syntax is:and the rows and columns to extract. The syntax is:

sub_matrix = matrix ( r1 : rn , c1 : cn ) ;sub_matrix = matrix ( r1 : rn , c1 : cn ) ;
sub_matrix = matrix ( r1 : rn , : ) ;sub_matrix = matrix ( r1 : rn , : ) ;
sub_matrix = matrix ( : , c1 : cn ) ;sub_matrix = matrix ( : , c1 : cn ) ;
sub_matrix = matrix ( r1 : dr : rn , c1 : dc : cn ) ;sub_matrix = matrix ( r1 : dr : rn , c1 : dc : cn ) ;
where where r1 r1 and and rnrn specify the beginning and ending rows specify the beginning and ending rows
and and c1c1 and and cncn specify the beginning and ending specify the beginning and ending
columns to be extracted to make the new matrix. columns to be extracted to make the new matrix.
The terms The terms drdr and and dc dc define spacing different than one.define spacing different than one.
matrix.mmatrix.m

““ContinuousContinuous”” functions functions
Numerically, we cannot represent a general continuous function Numerically, we cannot represent a general continuous function
(x,f(x)) because it requires handling infinite data (for each point in (x,f(x)) because it requires handling infinite data (for each point in
the range, we need to keep f(x)). Instead, we represent a function the range, we need to keep f(x)). Instead, we represent a function
by its values at a finite number of data points (x_i,f(x_i)), where the by its values at a finite number of data points (x_i,f(x_i)), where the
series of points {x_i} is typically referred to as the sampling points or series of points {x_i} is typically referred to as the sampling points or
the grid points. Accordingly, the "continuous" functions in Matlab the grid points. Accordingly, the "continuous" functions in Matlab
accepts a vector of point {x_i} and return a vector of values {f(x_i)}. accepts a vector of point {x_i} and return a vector of values {f(x_i)}.
Some functionsSome functions

sqrtsqrt

loglog

cos/acos/sin/asin etccos/acos/sin/asin etc

exp - exponentialexp - exponential

absabs

signsign

normnorm

sumsum

prod - productprod - product

PlottingPlotting
MATLAB will plot one vector vs. another. The first one will be treated MATLAB will plot one vector vs. another. The first one will be treated
as the abscissa (or x) vector and the second as the ordinate (or y) as the abscissa (or x) vector and the second as the ordinate (or y)
vector. The vectors have to be the same length.vector. The vectors have to be the same length.
MATLAB will also plot a vector vs. its own index. The index will be MATLAB will also plot a vector vs. its own index. The index will be
treated as the abscissa vector. Given a vector treated as the abscissa vector. Given a vector ““timetime”” and a vector and a vector
““distdist”” we could say: we could say:
>> plot (time, dist) >> plot (time, dist) % plotting versus time % plotting versus time
>> plot (time + i*dist) >> plot (time + i*dist) % plotting versus time % plotting versus time
>> plot (dist)>> plot (dist) % plotting versus index% plotting versus index
Sometime we want to see it with different color\line stileSometime we want to see it with different color\line stile
>> plot (time, dist, line_characteristics)>> plot (time, dist, line_characteristics)
And sometime we want to plot few functions in graphsAnd sometime we want to plot few functions in graphs
>> plot(…), hold, plot(…)>> plot(…), hold, plot(…)
>> plot(t,d1,l_c1, t,d2, l_c2)>> plot(t,d1,l_c1, t,d2, l_c2)
To split page to several axes check useTo split page to several axes check use
>> subplot (rows, cols, place)>> subplot (rows, cols, place)

PlottingPlotting
There are commands in MATLAB to "annotate" a plot to put on axis There are commands in MATLAB to "annotate" a plot to put on axis
labels, titles, and legends. For example:labels, titles, and legends. For example:
To put a label on the axes we would use:To put a label on the axes we would use:
>> xlabel ('X-axis label')>> xlabel ('X-axis label')
>> ylabel ('Y-axis label')>> ylabel ('Y-axis label')
To put a title on the plot, we would use:To put a title on the plot, we would use:
>> title ('Title of my plot')>> title ('Title of my plot')
To distinct between function in the graph use:To distinct between function in the graph use:
>> legend(legend_1, legend_2)>> legend(legend_1, legend_2)
plotting.mplotting.m

Flow control (condition)Flow control (condition)
An if - elseif - else structure. (Note that elseif is An if - elseif - else structure. (Note that elseif is oneone word) word)
ifif expression1 expression1
statements1statements1
elseifelseif expression2 expression2
statements2statements2
elseelse
statements3statements3
endend
An switch-case structureAn switch-case structure
switchswitch switch_expr switch_expr
casecase case_expr case_expr
statement, ..., statementstatement, ..., statement
casecase {case_expr1, case_expr2, case_expr3, ...} {case_expr1, case_expr2, case_expr3, ...}
statement, ..., statementstatement, ..., statement
otherwiseotherwise
statement, ..., statementstatement, ..., statement
endend

Flow control (loops)Flow control (loops)
A for loop in MATLABA for loop in MATLAB
forfor ind = 1:100ind = 1:100
b(ind)=sin(ind/10)b(ind)=sin(ind/10)
endend
Alternative (Most of the loops can be avoided!!!): Alternative (Most of the loops can be avoided!!!):
x=0.1:0.1:10; x=0.1:0.1:10;
b=sin(x); b=sin(x);
A while loop inA while loop in
whilewhile x <= 10x <= 10
% execute these commands% execute these commands
endend

M-FilesM-Files
An An M-fileM-file might be used as a might be used as a scriptscript, i.e. file consist set , i.e. file consist set
of statementsof statements
In additional, one use M-files to write In additional, one use M-files to write functionfunction, in this , in this
case the file starts with function definition like: case the file starts with function definition like:
function y = f(x)function y = f(x)
function [u,v] = f(x,y,z)function [u,v] = f(x,y,z)
File name File name and the and the name of function name of function in the file are in the file are
usually usually identicalidentical, however while they are different, , however while they are different,
MATLAB use file name to call function.MATLAB use file name to call function.
If you add additional function in same M-file, it If you add additional function in same M-file, it
considered sub-function and might be called from inside considered sub-function and might be called from inside
the M-file only. Only the first function might be called the M-file only. Only the first function might be called
from outside.from outside.

Saving ResultsSaving Results
We can save all our results for future referenceWe can save all our results for future reference. .
The commandThe command
diary diary ‘‘FileName' FileName'
saves all output to command window into the FileName.txt file until saves all output to command window into the FileName.txt file until
this option is turned off by the commandthis option is turned off by the command
diary offdiary off
The following commands save & load the entire workspace The following commands save & load the entire workspace
into the file 'MyMatFile.mat'into the file 'MyMatFile.mat'

save 'MyMatFile' save 'MyMatFile'

load 'MyMatFile' load 'MyMatFile'

save 'x.mat' x save 'x.mat' x % % save a specific variablesave a specific variable
saving in ASCII format:saving in ASCII format:

x = (-1:0.4:1)' ;x = (-1:0.4:1)' ;y = sin(x*pi) y = sin(x*pi)

var = [x y] var = [x y] % double-column % double-column

save 'my_sin.dat' -ASCII -double varsave 'my_sin.dat' -ASCII -double var % %Save in 16-digit ASCII formatSave in 16-digit ASCII format

MATLAB also have humorMATLAB also have humor
whywhy% try this command% try this command

The EndThe End
Tags