SlideShare une entreprise Scribd logo
1  sur  7
Télécharger pour lire hors ligne
MATLAB Tutorial
You need a small number of basic commands to start using MATLAB. This short tutorial
describes those fundamental commands. You need to create vectors and matrices, to change
them, and to operate with them. Those are all short high-level commands, because MATLAB
constantly works with matrices. I believe that you will like the power that this software gives,
to do linear algebra by a series of short instructions:
       create E            create u          change E           multiply E u
      E = eye(3)         u = E (: 1)        E (3 1) = 5          v=E u
     2          3           2 3             2          3           2 3
        1 0 0                 1               1 0 0                  1
     40 1 05                405             40 1 05                405
        0 0 1                 0               5 0 1                  5
The word eye stands for the identity matrix. The submatrix u = E (: 1) picks out column 1.
The instruction E (3 1) = 5 resets the (3 1) entry to 5. The command E u multiplies the
matrices E and u. All these commands are repeated in our list below. Here is an example
of inverting a matrix and solving a linear system:
            create A            create b           invert A           solve Ax = b
     A = ones(3) + eye(3) b = A(: 3)              C = inv(A)           x = Anb or
          2          3           2 3 2                            3 x 2 C3 b
                                                                          =
             2 1 1                 1            :75 ;:25 ;:25               0
          41 2 15                4 1 5 4 ;:25 :75 ;:25 5                  405
                                                                             





                                                                                 





             1 1 2                 2          ;:25 ;:25       :75           1





The matrix of all ones was added to eye(3), and b is its third column. Then inv(A) produces
the inverse matrix (normally in decimals for fractions use format rat ). The system Ax = b
is solved by x = inv(A) b, which is the slow way. The backslash command x = Anb uses
Gaussian elimination if A is square and never computes the inverse matrix. When the right
side b equals the third column of A, the solution x must be 0 0 1] . (The transpose symbol 0
                                                                    0



makes x a column vector.) Then A x picks out the third column of A, and we have Ax = b.
    Here are a few comments. The comment symbol is %:
  % The symbols a and A are di erent : MATLAB is case-sensitive.
  % Type help slash for a description of how to use the backslash symbol. The word help
    can be followed by a MATLAB symbol or command name or M- le name.

                                               1
Note: The command name is upper case in the description given by help, but must be
    lower case in actual use. And the backslash Anb is di erent when A is not square.
  % To display all 16 digits type format long. The normal format short gives 4 digits after
    the decimal.
  % A semicolon after a command avoids display of the result.
    A = ones(3) will not display the 3 3 identity matrix.
  % Use the up-arrow cursor to return to previous commands.

How to input a row or column vector
 u = 2 4 5]        has one row with three components (a 1 3 matrix)   





 v = 2 4 5]        has three rows separated by semicolons (a 3 1 matrix)           





 v = 2 4 5]0
                   or v = u transposes u to produce the same v
                           0




 w = 2:5           generates the row vector w = 2 3 4 5] with unit steps   





 u = 1:2:7         takes steps of 2 to give u = 1 3 5 7]   





How to input a matrix (a row at a time)
 A = 1 2 3 4 5 6] has two rows (always a semicolon between rows)
 A= 123           also produces the matrix A but is harder to type
     4 5 6]
                                                                               





               





 B = 1 2 3 4 5 6] is the transpose of A. Thus AT is A in MATLAB
                      0                                        0




How to create special matrices
diag(v) produces the diagonal matrix with vector v on its diagonal
toeplitz(v) gives the symmetric constant-diagonal matrix with v as rst row and rst col-
     umn
toeplitz(w v) gives the constant-diagonal matrix with w as rst column and v as rst row
ones(n) gives an n n matrix of ones
                                                  2
zeros(n) gives an n n matrix of zeros
eye(n) gives the n n identity matrix
rand(n) gives an n n matrix with random entries between 0 and 1 (uniform distribution)
randn(n) gives an n n matrix with normally distributed entries (mean 0 and variance 1)
ones(m n) zeros(m n) rand(m n) give m n matrices
ones(size(A)) zeros(size(A)) eye(size(A)) give matrices of the same shape as A
How to change entries in a given matrix A
 A(3 2) = 7 resets the (3 2) entry to equal 7
 A(3 :) = v resets the third row to equal v
 A(: 2) = w resets the second column to equal w
   The colon symbol : stands for all (all columns or all rows)
  A( 2 3] :) = A( 3 2] :) exchanges rows 2 and 3 of A

How to create submatrices of an m � n matrix A
 A(i j )        returns the (i j ) entry of the matrix A (scalar = 1 1 matrix)
 A(i :)         returns the ith row of A (as row vector)
                                                                             





 A(: j )        returns the j th column of A (as column vector)
                                                         





 A(2 : 4 3 : 7) returns rows from 2 to 4 and columns from 3 to 7 (as 3 5 matrix)
                                                                 





 A( 2 4] :)     returns rows 2 and 4 and all columns (as 2 n matrix)
                                                                                 





 A(:)           returns one long column formed from the columns of A (mn 1 matrix)
                                                                         





triu(A) sets all entries below the main diagonal to zero (upper triangular)
                                                                                     





tril(A) sets all entries above the main diagonal to zero (lower triangular)
Matrix multiplication and inversion
 A B gives the matrix product AB (if A can multiply B )
 A: B gives the entry-by-entry product (if size(A) = size(B ))
 inv(A) gives A 1 if A is square and invertible
                   ;



 pinv(A) gives the pseudoinverse of A
 AnB       gives inv(A) B if inv(A) exists: backslash is left division
 x = Anb gives the solution to Ax = b if inv(A) exists
   See help slash when A is a rectangular matrix!
                                             3
Numbers and matrices associated with A
det(A) is the determinant (if A is a square matrix)
rank(A) is the rank (number of pivots = dimension of row space and of column space)
size(A) is the pair of numbers m n]
trace(A) is the trace = sum of diagonal entries = sum of eigenvalues
null(A) is a matrix whose n ; r columns are an orthogonal basis for the nullspace of A
orth(A) is a matrix whose r columns are an orthogonal basis for the column space of A

Examples
E = eye(4) E (2 1) = ;3 creates a 4 4 elementary elimination matrix
E A subtracts 3 times row 1 of A from row 2.
B = A b] creates the augmented matrix with b as extra column
E = eye(3) P = E ( 2 1 3] :) creates a permutation matrix
Note that triu(A) + tril(A) ; diag(diag(A)) equals A

Built-in M- les for matrix factorizations (all important!)
  L U P ] = lu(A) gives three matrices with PA = LU
 e = eig(A) is a vector containing the eigenvalues of A
  S E ] = eig(A) gives a diagonal eigenvalue matrix E and eigenvector matrix S with AS =
     SE . If A is not diagonalizable (too few eigenvectors) then S is not invertible.
  Q R] = qr(A) gives an m m orthogonal matrix Q and m n triangular R with A = QR

Creating M- les
M- les are text les ending with .m which MATLAB uses for functions and scripts. A script
is a sequence of commands which may be executed often, and can be placed in an m- le so
the commands do not have to be retyped. MATLAB's demos are examples of these scripts.
An example is the demo called house. Most of MATLAB's functions are actually m- les,
and can be viewed by writing type xxx where xxx is the name of the function.


                                           4
To write your own scripts or functions, you have to create a new text le with any name
you like, provided it ends with .m, so MATLAB will recognize it. Text les can be created,
edited and saved with any text editor, like emacs, EZ, or vi. A script le is simply a list of
MATLAB commands. When the le name is typed at the MATLAB prompt, the contents of
the le will be executed. For an m- le to be a function it must start with the word function
followed by the output variables in brackets, the function name, and the input variables.

Examples
function C]=mult(A)
r=rank(A)
C=A A 0




Save the above commands into a text le named mult.m Then this funtion will take a
matrix A and return only the matrix product C . The variable r is not returned because it
was not included as an output variable. The commands are followed by so that they will
not be printed to the MATLAB window every time they are executed. It is useful when
dealing with large matrices. Here is another example:
function V,D,r]=properties(A)
% This function nds the rank, eigenvalues and eigenvectors of A
 m,n]=size(A)
if m==n
 V,D]=eig(A)
r=rank(A)
else
disp('Error: The matrix must be square')
end
Here the function takes the matrix A as input and only returns two matrices and the rank
as output. The % is used as a comment. The function checks to see if the input ma-
trix is square and then nds the rank, eigenvalues and eigenvectors of a matrix A. Typing
properties(A) only returns the rst output, V, the matrix of eigenvectors. You must type
 V,D,r]=properties(A) to get all three outputs.




                                             5
Keeping a diary of your work
The command diary(' le') tells MATLAB to record everything done in the MATLAB
window, and save the results in the text le named ' le'. Typing diary on or diary o
toggles the recording. Old diary les can be viewed using a text editor, or printed using lpr
in unix. In MATLAB, they can be viewed using the type le command.

Saving your variables and matrices
The command diary saves the commands you typed as well as MATLAB's output, but it
does not save the content of your variables and matrices. These variables can be listed by
the command whos which also lists the sizes of the matrices. The command save 'xxx'
will save the matrices and all variables listed by the whos command into the le named
xxx. MATLAB labels these les with a .mat extension instead of .m which are scripts or
functions. xxx.mat les can be read by MATLAB at a later time by typing load xxx.


Graphics
The simplest command is plot(x y) which uses two vectors x and y of the same length. The
points (xi yi) will be plotted and connected by solid lines.
   If no vector x is given, MATLAB assumes that x(i) = i. Then plot(y) has equal spacing
on the x-axis: the points are (i y(i)).
   The type and color of the line between points can be changed by a third argument. The
default with no argument is a solid black line {". Use help plot for many options, we indi-
cate only a few:
MATLAB 5: plot(x y r+ : ) plots in r = red with + for points and dotted line
                       0         0




MATLAB 4: plot(x y     0
                           ;; )
                             0
                                     is a dashed line and plot(x y ) is a dotted line
                                                                               0       0




   You can omit the lines and plot only the discrete points in di erent ways:
plot(x y o ) gives circles. Other options are + or or
         0   0                                             0   0   0   0   0       0




   For two graphs on the same axes use plot(x y X Y ). Replace plot by loglog or
semilogy or semilogx to change one or both axes to logarithmic scale. The command

                                                   6
axis ( a b c d]) will scale the graph to lie in the rectangle a x b, c y d. To title the
graph or label the x-axis or the y-axis, put the desired label in quotes as in these examples:
    title (`height of satellite') xlabel (`time in seconds') y label (`height in meters')
    The command hold keeps the current graph as you plot a new graph. Repeating hold
will clear the screen. To print, or save the graphics window in a le, see help print or use
                        print -Pprintername        print -d lename




                                              7

Contenu connexe

Tendances

6.4 inverse matrices
6.4 inverse matrices6.4 inverse matrices
6.4 inverse matrices
math260
 
Null space, Rank and nullity theorem
Null space, Rank and nullity theoremNull space, Rank and nullity theorem
Null space, Rank and nullity theorem
Ronak Machhi
 
6.3 matrix algebra
6.3 matrix algebra6.3 matrix algebra
6.3 matrix algebra
math260
 
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeksBeginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
JinTaek Seo
 
Inverse Matrix & Determinants
Inverse Matrix & DeterminantsInverse Matrix & Determinants
Inverse Matrix & Determinants
itutor
 
Lesson 5: Matrix Algebra (slides)
Lesson 5: Matrix Algebra (slides)Lesson 5: Matrix Algebra (slides)
Lesson 5: Matrix Algebra (slides)
Matthew Leingang
 
Linear Algebra and Matrix
Linear Algebra and MatrixLinear Algebra and Matrix
Linear Algebra and Matrix
itutor
 

Tendances (19)

6.4 inverse matrices
6.4 inverse matrices6.4 inverse matrices
6.4 inverse matrices
 
Null space, Rank and nullity theorem
Null space, Rank and nullity theoremNull space, Rank and nullity theorem
Null space, Rank and nullity theorem
 
6.3 matrix algebra
6.3 matrix algebra6.3 matrix algebra
6.3 matrix algebra
 
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeksBeginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
Beginning direct3d gameprogrammingmath05_matrices_20160515_jintaeks
 
Bba i-bm-u-2- matrix -
Bba i-bm-u-2- matrix -Bba i-bm-u-2- matrix -
Bba i-bm-u-2- matrix -
 
Inverse Matrix & Determinants
Inverse Matrix & DeterminantsInverse Matrix & Determinants
Inverse Matrix & Determinants
 
Lesson 5: Matrix Algebra (slides)
Lesson 5: Matrix Algebra (slides)Lesson 5: Matrix Algebra (slides)
Lesson 5: Matrix Algebra (slides)
 
Matrices ppt
Matrices pptMatrices ppt
Matrices ppt
 
matrices and determinantes
matrices and determinantes matrices and determinantes
matrices and determinantes
 
Linear Algebra and Matrix
Linear Algebra and MatrixLinear Algebra and Matrix
Linear Algebra and Matrix
 
matrix algebra
matrix algebramatrix algebra
matrix algebra
 
Matrices and determinants
Matrices and determinantsMatrices and determinants
Matrices and determinants
 
Presentation on matrix
Presentation on matrixPresentation on matrix
Presentation on matrix
 
Matrix2 english
Matrix2 englishMatrix2 english
Matrix2 english
 
Matrix
MatrixMatrix
Matrix
 
Matlab ch1 (1)
Matlab ch1 (1)Matlab ch1 (1)
Matlab ch1 (1)
 
matrices and algbra
matrices and algbramatrices and algbra
matrices and algbra
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 
Matrix algebra
Matrix algebraMatrix algebra
Matrix algebra
 

En vedette

Autoretrats dels felins i les felines
Autoretrats dels felins i les felinesAutoretrats dels felins i les felines
Autoretrats dels felins i les felines
esther669
 
Ktima Chantzi Company Presentation EN
Ktima Chantzi Company Presentation EN   Ktima Chantzi Company Presentation EN
Ktima Chantzi Company Presentation EN
ktimamarketing
 
Questions 1 27
Questions 1 27Questions 1 27
Questions 1 27
clarodgers
 
Декада инвалидов
Декада инвалидовДекада инвалидов
Декада инвалидов
Nikita Kudelin
 
¨قوة التفكير
¨قوة التفكير¨قوة التفكير
¨قوة التفكير
Mohamed Yaser
 
Compliance Software
Compliance SoftwareCompliance Software
Compliance Software
cvrhijn
 
Theory Of Wing Sections
Theory  Of  Wing  SectionsTheory  Of  Wing  Sections
Theory Of Wing Sections
Mohamed Yaser
 
CIS 2303 LO2 Part 3
CIS 2303 LO2 Part 3CIS 2303 LO2 Part 3
CIS 2303 LO2 Part 3
Ahmad Ammari
 

En vedette (20)

Autoretrats dels felins i les felines
Autoretrats dels felins i les felinesAutoretrats dels felins i les felines
Autoretrats dels felins i les felines
 
Software Series 4
Software Series  4Software Series  4
Software Series 4
 
ค่าเช่าบ้านพลเรือน
ค่าเช่าบ้านพลเรือนค่าเช่าบ้านพลเรือน
ค่าเช่าบ้านพลเรือน
 
бизнес план 3
бизнес план 3бизнес план 3
бизнес план 3
 
Ktima Chantzi Company Presentation EN
Ktima Chantzi Company Presentation EN   Ktima Chantzi Company Presentation EN
Ktima Chantzi Company Presentation EN
 
David
DavidDavid
David
 
Questions 1 27
Questions 1 27Questions 1 27
Questions 1 27
 
AngularJS: A framework to make your life easier
AngularJS: A framework to make your life easierAngularJS: A framework to make your life easier
AngularJS: A framework to make your life easier
 
Декада инвалидов
Декада инвалидовДекада инвалидов
Декада инвалидов
 
Kt24
Kt24Kt24
Kt24
 
Ao thuat
Ao thuatAo thuat
Ao thuat
 
¨قوة التفكير
¨قوة التفكير¨قوة التفكير
¨قوة التفكير
 
Systemy operacyjne
Systemy operacyjneSystemy operacyjne
Systemy operacyjne
 
Jelly berry
Jelly berryJelly berry
Jelly berry
 
Buscando trabajo
Buscando trabajoBuscando trabajo
Buscando trabajo
 
Russian Neurosurgical Journal; Vol 3, No 4
Russian Neurosurgical Journal; Vol 3, No 4Russian Neurosurgical Journal; Vol 3, No 4
Russian Neurosurgical Journal; Vol 3, No 4
 
Compliance Software
Compliance SoftwareCompliance Software
Compliance Software
 
Harbor UCLA Neuro-Radiology -- Case 3
Harbor UCLA Neuro-Radiology -- Case 3Harbor UCLA Neuro-Radiology -- Case 3
Harbor UCLA Neuro-Radiology -- Case 3
 
Theory Of Wing Sections
Theory  Of  Wing  SectionsTheory  Of  Wing  Sections
Theory Of Wing Sections
 
CIS 2303 LO2 Part 3
CIS 2303 LO2 Part 3CIS 2303 LO2 Part 3
CIS 2303 LO2 Part 3
 

Similaire à 1

INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
Devaraj Chilakala
 
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxMATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
andreecapon
 

Similaire à 1 (20)

Matlab cheatsheet
Matlab cheatsheetMatlab cheatsheet
Matlab cheatsheet
 
Matlab practice
Matlab practiceMatlab practice
Matlab practice
 
1. Introduction.pptx
1. Introduction.pptx1. Introduction.pptx
1. Introduction.pptx
 
Chapter 4: Vector Spaces - Part 4/Slides By Pearson
Chapter 4: Vector Spaces - Part 4/Slides By PearsonChapter 4: Vector Spaces - Part 4/Slides By Pearson
Chapter 4: Vector Spaces - Part 4/Slides By Pearson
 
Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4Introduction to matlab lecture 2 of 4
Introduction to matlab lecture 2 of 4
 
Matlab colon notation
Matlab colon notationMatlab colon notation
Matlab colon notation
 
ArrayBasics.ppt
ArrayBasics.pptArrayBasics.ppt
ArrayBasics.ppt
 
INTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptxINTRODUCTION TO MATLAB presentation.pptx
INTRODUCTION TO MATLAB presentation.pptx
 
Matlab tut3
Matlab tut3Matlab tut3
Matlab tut3
 
Matlab matrices and arrays
Matlab matrices and arraysMatlab matrices and arrays
Matlab matrices and arrays
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
Matrices, Arrays and Vectors in MATLAB
Matrices, Arrays and Vectors in MATLABMatrices, Arrays and Vectors in MATLAB
Matrices, Arrays and Vectors in MATLAB
 
Commands list
Commands listCommands list
Commands list
 
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxMATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
matlab_tutorial.ppt
matlab_tutorial.pptmatlab_tutorial.ppt
matlab_tutorial.ppt
 
Matlab
MatlabMatlab
Matlab
 
Matlab cheatsheet
Matlab cheatsheetMatlab cheatsheet
Matlab cheatsheet
 
Matlab booklet
Matlab bookletMatlab booklet
Matlab booklet
 
Matlab Tutorial
Matlab TutorialMatlab Tutorial
Matlab Tutorial
 

Plus de Mohamed Yaser

7 habits of highly effective people
7 habits of highly effective people7 habits of highly effective people
7 habits of highly effective people
Mohamed Yaser
 
Us navy introduction to helicopter aerodynamics workbook cnatra p-401 [us n...
Us navy   introduction to helicopter aerodynamics workbook cnatra p-401 [us n...Us navy   introduction to helicopter aerodynamics workbook cnatra p-401 [us n...
Us navy introduction to helicopter aerodynamics workbook cnatra p-401 [us n...
Mohamed Yaser
 
Aerodynamics of the helicopter 2
Aerodynamics of the helicopter 2Aerodynamics of the helicopter 2
Aerodynamics of the helicopter 2
Mohamed Yaser
 
Seddon j. basic helicopter aerodynamics [bsp prof. books 1990]
Seddon j.   basic helicopter aerodynamics [bsp prof. books 1990]Seddon j.   basic helicopter aerodynamics [bsp prof. books 1990]
Seddon j. basic helicopter aerodynamics [bsp prof. books 1990]
Mohamed Yaser
 
The 10 natural_laws_of_successful_time_and_life_management
The 10 natural_laws_of_successful_time_and_life_managementThe 10 natural_laws_of_successful_time_and_life_management
The 10 natural_laws_of_successful_time_and_life_management
Mohamed Yaser
 
حياة بلا توتر
حياة بلا توترحياة بلا توتر
حياة بلا توتر
Mohamed Yaser
 
المفاتيح العشرة للنجاح
المفاتيح العشرة للنجاحالمفاتيح العشرة للنجاح
المفاتيح العشرة للنجاح
Mohamed Yaser
 
¨قوة التفكير
¨قوة التفكير¨قوة التفكير
¨قوة التفكير
Mohamed Yaser
 
The 10 Natural Laws Of Successful Time And Life Management
The 10  Natural  Laws Of  Successful  Time And  Life  ManagementThe 10  Natural  Laws Of  Successful  Time And  Life  Management
The 10 Natural Laws Of Successful Time And Life Management
Mohamed Yaser
 
Copy of book1 in c++
Copy of book1  in  c++Copy of book1  in  c++
Copy of book1 in c++
Mohamed Yaser
 
structure for aerospace eng
structure for aerospace engstructure for aerospace eng
structure for aerospace eng
Mohamed Yaser
 
realitivistic relativity 2.0
  realitivistic relativity 2.0  realitivistic relativity 2.0
realitivistic relativity 2.0
Mohamed Yaser
 
Lec10 MECH ENG STRucture
Lec10   MECH ENG  STRuctureLec10   MECH ENG  STRucture
Lec10 MECH ENG STRucture
Mohamed Yaser
 
Lec9 MECH ENG STRucture
Lec9   MECH ENG  STRuctureLec9   MECH ENG  STRucture
Lec9 MECH ENG STRucture
Mohamed Yaser
 

Plus de Mohamed Yaser (20)

7 habits of highly effective people
7 habits of highly effective people7 habits of highly effective people
7 habits of highly effective people
 
Us navy introduction to helicopter aerodynamics workbook cnatra p-401 [us n...
Us navy   introduction to helicopter aerodynamics workbook cnatra p-401 [us n...Us navy   introduction to helicopter aerodynamics workbook cnatra p-401 [us n...
Us navy introduction to helicopter aerodynamics workbook cnatra p-401 [us n...
 
Aerodynamics of the helicopter 2
Aerodynamics of the helicopter 2Aerodynamics of the helicopter 2
Aerodynamics of the helicopter 2
 
Seddon j. basic helicopter aerodynamics [bsp prof. books 1990]
Seddon j.   basic helicopter aerodynamics [bsp prof. books 1990]Seddon j.   basic helicopter aerodynamics [bsp prof. books 1990]
Seddon j. basic helicopter aerodynamics [bsp prof. books 1990]
 
The 10 natural_laws_of_successful_time_and_life_management
The 10 natural_laws_of_successful_time_and_life_managementThe 10 natural_laws_of_successful_time_and_life_management
The 10 natural_laws_of_successful_time_and_life_management
 
حياة بلا توتر
حياة بلا توترحياة بلا توتر
حياة بلا توتر
 
فن التفاوض
فن التفاوضفن التفاوض
فن التفاوض
 
المفاتيح العشرة للنجاح
المفاتيح العشرة للنجاحالمفاتيح العشرة للنجاح
المفاتيح العشرة للنجاح
 
أدارة الوقت
أدارة الوقتأدارة الوقت
أدارة الوقت
 
¨قوة التفكير
¨قوة التفكير¨قوة التفكير
¨قوة التفكير
 
The 10 Natural Laws Of Successful Time And Life Management
The 10  Natural  Laws Of  Successful  Time And  Life  ManagementThe 10  Natural  Laws Of  Successful  Time And  Life  Management
The 10 Natural Laws Of Successful Time And Life Management
 
F- 20
F- 20F- 20
F- 20
 
Copy of book1 in c++
Copy of book1  in  c++Copy of book1  in  c++
Copy of book1 in c++
 
structure for aerospace eng
structure for aerospace engstructure for aerospace eng
structure for aerospace eng
 
Tutorial 2
Tutorial     2Tutorial     2
Tutorial 2
 
Tutorial
TutorialTutorial
Tutorial
 
realitivistic relativity 2.0
  realitivistic relativity 2.0  realitivistic relativity 2.0
realitivistic relativity 2.0
 
Lec5
Lec5Lec5
Lec5
 
Lec10 MECH ENG STRucture
Lec10   MECH ENG  STRuctureLec10   MECH ENG  STRucture
Lec10 MECH ENG STRucture
 
Lec9 MECH ENG STRucture
Lec9   MECH ENG  STRuctureLec9   MECH ENG  STRucture
Lec9 MECH ENG STRucture
 

1

  • 1. MATLAB Tutorial You need a small number of basic commands to start using MATLAB. This short tutorial describes those fundamental commands. You need to create vectors and matrices, to change them, and to operate with them. Those are all short high-level commands, because MATLAB constantly works with matrices. I believe that you will like the power that this software gives, to do linear algebra by a series of short instructions: create E create u change E multiply E u E = eye(3) u = E (: 1) E (3 1) = 5 v=E u 2 3 2 3 2 3 2 3 1 0 0 1 1 0 0 1 40 1 05 405 40 1 05 405 0 0 1 0 5 0 1 5 The word eye stands for the identity matrix. The submatrix u = E (: 1) picks out column 1. The instruction E (3 1) = 5 resets the (3 1) entry to 5. The command E u multiplies the matrices E and u. All these commands are repeated in our list below. Here is an example of inverting a matrix and solving a linear system: create A create b invert A solve Ax = b A = ones(3) + eye(3) b = A(: 3) C = inv(A) x = Anb or 2 3 2 3 2 3 x 2 C3 b = 2 1 1 1 :75 ;:25 ;:25 0 41 2 15 4 1 5 4 ;:25 :75 ;:25 5 405 1 1 2 2 ;:25 ;:25 :75 1 The matrix of all ones was added to eye(3), and b is its third column. Then inv(A) produces the inverse matrix (normally in decimals for fractions use format rat ). The system Ax = b is solved by x = inv(A) b, which is the slow way. The backslash command x = Anb uses Gaussian elimination if A is square and never computes the inverse matrix. When the right side b equals the third column of A, the solution x must be 0 0 1] . (The transpose symbol 0 0 makes x a column vector.) Then A x picks out the third column of A, and we have Ax = b. Here are a few comments. The comment symbol is %: % The symbols a and A are di erent : MATLAB is case-sensitive. % Type help slash for a description of how to use the backslash symbol. The word help can be followed by a MATLAB symbol or command name or M- le name. 1
  • 2. Note: The command name is upper case in the description given by help, but must be lower case in actual use. And the backslash Anb is di erent when A is not square. % To display all 16 digits type format long. The normal format short gives 4 digits after the decimal. % A semicolon after a command avoids display of the result. A = ones(3) will not display the 3 3 identity matrix. % Use the up-arrow cursor to return to previous commands. How to input a row or column vector u = 2 4 5] has one row with three components (a 1 3 matrix) v = 2 4 5] has three rows separated by semicolons (a 3 1 matrix) v = 2 4 5]0 or v = u transposes u to produce the same v 0 w = 2:5 generates the row vector w = 2 3 4 5] with unit steps u = 1:2:7 takes steps of 2 to give u = 1 3 5 7] How to input a matrix (a row at a time) A = 1 2 3 4 5 6] has two rows (always a semicolon between rows) A= 123 also produces the matrix A but is harder to type 4 5 6] B = 1 2 3 4 5 6] is the transpose of A. Thus AT is A in MATLAB 0 0 How to create special matrices diag(v) produces the diagonal matrix with vector v on its diagonal toeplitz(v) gives the symmetric constant-diagonal matrix with v as rst row and rst col- umn toeplitz(w v) gives the constant-diagonal matrix with w as rst column and v as rst row ones(n) gives an n n matrix of ones 2
  • 3. zeros(n) gives an n n matrix of zeros eye(n) gives the n n identity matrix rand(n) gives an n n matrix with random entries between 0 and 1 (uniform distribution) randn(n) gives an n n matrix with normally distributed entries (mean 0 and variance 1) ones(m n) zeros(m n) rand(m n) give m n matrices ones(size(A)) zeros(size(A)) eye(size(A)) give matrices of the same shape as A How to change entries in a given matrix A A(3 2) = 7 resets the (3 2) entry to equal 7 A(3 :) = v resets the third row to equal v A(: 2) = w resets the second column to equal w The colon symbol : stands for all (all columns or all rows) A( 2 3] :) = A( 3 2] :) exchanges rows 2 and 3 of A How to create submatrices of an m � n matrix A A(i j ) returns the (i j ) entry of the matrix A (scalar = 1 1 matrix) A(i :) returns the ith row of A (as row vector) A(: j ) returns the j th column of A (as column vector) A(2 : 4 3 : 7) returns rows from 2 to 4 and columns from 3 to 7 (as 3 5 matrix) A( 2 4] :) returns rows 2 and 4 and all columns (as 2 n matrix) A(:) returns one long column formed from the columns of A (mn 1 matrix) triu(A) sets all entries below the main diagonal to zero (upper triangular) tril(A) sets all entries above the main diagonal to zero (lower triangular) Matrix multiplication and inversion A B gives the matrix product AB (if A can multiply B ) A: B gives the entry-by-entry product (if size(A) = size(B )) inv(A) gives A 1 if A is square and invertible ; pinv(A) gives the pseudoinverse of A AnB gives inv(A) B if inv(A) exists: backslash is left division x = Anb gives the solution to Ax = b if inv(A) exists See help slash when A is a rectangular matrix! 3
  • 4. Numbers and matrices associated with A det(A) is the determinant (if A is a square matrix) rank(A) is the rank (number of pivots = dimension of row space and of column space) size(A) is the pair of numbers m n] trace(A) is the trace = sum of diagonal entries = sum of eigenvalues null(A) is a matrix whose n ; r columns are an orthogonal basis for the nullspace of A orth(A) is a matrix whose r columns are an orthogonal basis for the column space of A Examples E = eye(4) E (2 1) = ;3 creates a 4 4 elementary elimination matrix E A subtracts 3 times row 1 of A from row 2. B = A b] creates the augmented matrix with b as extra column E = eye(3) P = E ( 2 1 3] :) creates a permutation matrix Note that triu(A) + tril(A) ; diag(diag(A)) equals A Built-in M- les for matrix factorizations (all important!) L U P ] = lu(A) gives three matrices with PA = LU e = eig(A) is a vector containing the eigenvalues of A S E ] = eig(A) gives a diagonal eigenvalue matrix E and eigenvector matrix S with AS = SE . If A is not diagonalizable (too few eigenvectors) then S is not invertible. Q R] = qr(A) gives an m m orthogonal matrix Q and m n triangular R with A = QR Creating M- les M- les are text les ending with .m which MATLAB uses for functions and scripts. A script is a sequence of commands which may be executed often, and can be placed in an m- le so the commands do not have to be retyped. MATLAB's demos are examples of these scripts. An example is the demo called house. Most of MATLAB's functions are actually m- les, and can be viewed by writing type xxx where xxx is the name of the function. 4
  • 5. To write your own scripts or functions, you have to create a new text le with any name you like, provided it ends with .m, so MATLAB will recognize it. Text les can be created, edited and saved with any text editor, like emacs, EZ, or vi. A script le is simply a list of MATLAB commands. When the le name is typed at the MATLAB prompt, the contents of the le will be executed. For an m- le to be a function it must start with the word function followed by the output variables in brackets, the function name, and the input variables. Examples function C]=mult(A) r=rank(A) C=A A 0 Save the above commands into a text le named mult.m Then this funtion will take a matrix A and return only the matrix product C . The variable r is not returned because it was not included as an output variable. The commands are followed by so that they will not be printed to the MATLAB window every time they are executed. It is useful when dealing with large matrices. Here is another example: function V,D,r]=properties(A) % This function nds the rank, eigenvalues and eigenvectors of A m,n]=size(A) if m==n V,D]=eig(A) r=rank(A) else disp('Error: The matrix must be square') end Here the function takes the matrix A as input and only returns two matrices and the rank as output. The % is used as a comment. The function checks to see if the input ma- trix is square and then nds the rank, eigenvalues and eigenvectors of a matrix A. Typing properties(A) only returns the rst output, V, the matrix of eigenvectors. You must type V,D,r]=properties(A) to get all three outputs. 5
  • 6. Keeping a diary of your work The command diary(' le') tells MATLAB to record everything done in the MATLAB window, and save the results in the text le named ' le'. Typing diary on or diary o toggles the recording. Old diary les can be viewed using a text editor, or printed using lpr in unix. In MATLAB, they can be viewed using the type le command. Saving your variables and matrices The command diary saves the commands you typed as well as MATLAB's output, but it does not save the content of your variables and matrices. These variables can be listed by the command whos which also lists the sizes of the matrices. The command save 'xxx' will save the matrices and all variables listed by the whos command into the le named xxx. MATLAB labels these les with a .mat extension instead of .m which are scripts or functions. xxx.mat les can be read by MATLAB at a later time by typing load xxx. Graphics The simplest command is plot(x y) which uses two vectors x and y of the same length. The points (xi yi) will be plotted and connected by solid lines. If no vector x is given, MATLAB assumes that x(i) = i. Then plot(y) has equal spacing on the x-axis: the points are (i y(i)). The type and color of the line between points can be changed by a third argument. The default with no argument is a solid black line {". Use help plot for many options, we indi- cate only a few: MATLAB 5: plot(x y r+ : ) plots in r = red with + for points and dotted line 0 0 MATLAB 4: plot(x y 0 ;; ) 0 is a dashed line and plot(x y ) is a dotted line 0 0 You can omit the lines and plot only the discrete points in di erent ways: plot(x y o ) gives circles. Other options are + or or 0 0 0 0 0 0 0 0 For two graphs on the same axes use plot(x y X Y ). Replace plot by loglog or semilogy or semilogx to change one or both axes to logarithmic scale. The command 6
  • 7. axis ( a b c d]) will scale the graph to lie in the rectangle a x b, c y d. To title the graph or label the x-axis or the y-axis, put the desired label in quotes as in these examples: title (`height of satellite') xlabel (`time in seconds') y label (`height in meters') The command hold keeps the current graph as you plot a new graph. Repeating hold will clear the screen. To print, or save the graphics window in a le, see help print or use print -Pprintername print -d lename 7