##### Document Text Contents

Page 1

A VERY BASIC MATLAB PRIMER

JACEK POLEWCZAK

Contents

1. A Few Elementary Calculations 2

2. Finding Help in Matlab 2

3. Working with Arrays of Numbers 3

4. Creating Script Files and Simple Plots 4

5. Creating and Executing a Function File 5

6. Saving/Loading Data, Recording a Session, Clearing Variables, and More on Plotting 7

7. Matrices and Vectors 8

7.1. Appending or Deleting a Row or Column 10

7.2. Matrix Operations 11

7.3. Array Operations 12

7.4. Matrix Functions 13

8. Character Strings 14

8.1. eval Function 15

9. for and while Loops and if Conditionals 16

10. Interactive Input 18

11. Input/Output Commands 19

12. Linear Algebra 23

12.1. Solving Linear Square Systems 23

12.2. Gaussian Elimination 25

12.3. Inverses, Determinants, and Cramer’s Rule 26

12.4. Pseudoinverses or Generalized Inverses 28

12.5. Underdetermined and Overdetermined Linear Systems 29

12.6. Finding Eigenvalues and Eigenvectors 35

12.7. Generalized Eigenvectors 38

12.8. Matrix Factorizations, Matrix Powers and Exponentials 41

12.9. Characteristic Polynomial of a Matrix and Cayley-Hamilton Theorem 46

13. Curve Fitting and Interpolation 47

13.1. Hands-on Understanding of Curve Fitting Using Polynomial Functions 48

13.2. Interpolation 49

14. Solving Nonlinear Algebraic Equations 50

15. Numerical Integration - Quadrature 51

15.1. Quadrature For Double Integrals 52

16. Solving Ordinary Differential Equations 52

Date: Last updated November 2009.

Some of the examples in this tutorial are the modified versions of the items from Rudra Pratap’s, Getting started with Matlab,

Oxford University Press, 2002.

1

Page 2

2 JACEK POLEWCZAK

16.1. Solving Linear Systems of First Order Differential Equations 57

16.2. Linearization of a Double Pendulum 65

17. Use of Global Variables 68

18. Publishing Documents and Opening Web Pages in Matlab 69

19. How to Download the Matlab Files Used in this Tutorial 72

1. A Few Elementary Calculations

>> 2+4

ans =

6

Enter 2 + 4 and hit return/enter key.

>> x = 2+5

ans =

7

Assigning the value of an expression to a variable.

>> z= 3^4+log(pi)*cos(x);

>> z

81.8630

A semicolon suppresses screen output. You can re-

call the value of z by typing z

>> format short e

>> z

z =

8.1863e+01

The floating point output display is controlled by

the format command.

>> format long

>> z

z =

81.863014441556018

>> format short

>> z

z =

81.8630

>> quit Quit Matlab. Alternatively you can type exit com-

mand or select Exit Matlab from the File Menu.

For additional help type in Matlab: help format

2. Finding Help in Matlab

There are several ways to get help in Matlab:

• help functionname provides direct on-line help on the function whose eaxct name you know. For

example help help provides help on the function help.

• lookfor keyword provides a list functions with the string keyword in their description. For example,

>> lookfor prime

isprime - True for prime numbers.

factor - Prime factors.

primes - Generate list of prime numbers.

By clicking on isprime, factor, or primes additional help on those functions will be listed.

Page 36

36 JACEK POLEWCZAK

Also by checking

>> format rat; det(V)

ans =

-1121/1189

we observe that V−1 exists, with the property

>> format rat; V*D*inv(V)

ans =

8 1 6

3 5 7

4 9 2

>> A=magic(3)

A =

8 1 6

3 5 7

4 9 2

Thus, we have A = VDV−1. Furthermore, V−1AV =

D. Because of this last property, we say that the ma-

trix A is diagonalizable.

The eigenvalues and eigenvectors can be complex valued as the next example shows:

>> A=[0 -6 -1;6 2 -16;-5 20 -10]

A =

0 -6 -1

6 2 -16

-5 20 -10

>> format rat; [V,D]=eig(A)

V =

-383/460 899/4489 - 387/2777i 899/4489 + 387/2777i

-1071/3014 -753/3568 - 519/805i -753/3568 + 519/805i

-489/1151 -1736/2505 -1736/2505

D =

-2294/747 0 0

0 -1841/747 + 4277/243i 0

0 0 -1841/747 - 4277/243i

Not every n × n matrix A has n linearly independent eigenvectors. For example, it is easy to show that

matrix A =

[

0 1

0 0

]

has a double eigenvalue λ = 0 and only one eigenvector v =

[

1

0

]

.

One can prove that if n × n matrix A has n distinct eigenvalues λ1, λ2, . . . , λn, then A has n linearly

independent eigenvectors: K1, K2, . . . ,Kn. Furthermore, if V denotes n × n matrix whose columns are

eigenvectors K1, K2, . . . ,Kn, then

A = VDV−1 and D = V−1AV, where D =

λ1 0 · · · 0

0 λ2 · · · 0

...

...

0 0 · · · λn

Because of the identity V−1AV = D, we say that the matrix A is diagonalizable. An important class of

diagonalizable matrices are square symmetric matrices whose entries are real. A square matrix A is symmetric

if it is equal to its transpose, i.e., A = A′. In other words, if for A = (aij)i,j=1,2,...,n , we have aij = aji, for

i, j = 1, 2, . . . , n.

A matrix with repeated eigenvalues may still have a full set of linearly independent vectors, as the next

example shows:

Page 37

MATLAB PRIMER 37

>> A=[1 -2 2;-2 1 -2;2 -2 1]

A =

1 -2 2

-2 1 -2

2 -2 1

>> format rat; [V,D]=eig(A)

V =

-247/398 1145/2158 780/1351

279/1870 1343/1673 -780/1351

1040/1351 1013/3722 780/1351

D =

-1 0 0

0 -1 0

0 0 5

Matrix A has eigenvalues λ1 = λ2 = −1 and λ3 = 5.

A more readable expressions for the eigenvectors can be obtained by entering the command [P,J]=jordan(A)

(see Section 12.8.5 for more information on Jordan decomposition):

>> format rat; [P,J]=jordan(A)

P =

2/3 1/3 -1

1/3 -1/3 0

-1/3 1/3 1

J =

-1 0 0

0 5 0

0 0 -1

The columns of P represent the eigenvectors of A. Furthermore, after taking into account that eigenvectors

are determined up to multiplicative scalars, here are the eigenvalues and the corresponding eigenvectors:

λ1 = −1, K1 =

[

2

1

−1

]

; λ2 = 5, K2 =

[

1

−1

1

]

; λ2 = −1, K3 =

[

−1

0

1

]

.

As verified below, the first two columns of V (i.e., the eigenvectors corresponding to the repeated eigenvalue

−1) can be expressed as the linear combinations of the eigenvectors K1 and K3 :

>> format rat; [3*P(:,1) P(:,3)]\V(:,1)

ans =

279/1870 % c1

624/679 % c2

>> format rat; [3*P(:,1) P(:,3)]\V(:,2)

ans =

1343/1673 % c1

947/881 % c2

Consider the following non diagonalizable matrix:

Page 71

MATLAB PRIMER 71

As before, save the script in ex1_script_improved.m file (remember to place it in the working directory of

Matlab) and try it out. Alternatively, you can also download it from:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex1_script_improved.m

Once the Matlab script is running and placed in the current working directory of Matlab, you can publish it

using the following Matlab command:

>> publish(’ex1_script_improved’)

ex1_script_improved.html file will be created in html sub-directory of your current working directory.

You can view this newly created ex1_script_improved.html file in Matlab’s internal browser with the

command:

>> open html/ex1_script_improved.html

And here is the link to ex1_script_improved.html file:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex1_script_improved.html

After typesetting the LATEX file publish(’ex1_script_improved’,’latex’), its pdf output can be found

here:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex1_script_improved.pdf

The last example publishes the script in Example 3 of Section 16. The script uses an additional function file

ode3.m that can be downloaded from

http://www.csun.edu/~hcmth008/matlab_tutorial/ode3.m

and placed in the working Matlab directory.

Here is the corresponding Matlab script:

%% Nonlinear pendulum

%% The differential equation:

% $$\ddot{\theta}+\omega^2\sin\theta=0,\qquad \theta(0)=0,\qquad \dot{\theta}(0)=1.$$

%% The corresponding system of the first order differential equations:

% $$\frac{dz_1}{dt}=z_2,\,\,\frac{dz_2}{dt}=-\omega^2\sin(z_1),\,\, z_1(0)=0,\,\, z_2(0)=1.$$

%% Input initial conditions:

z0=[0,1];

%% Define the interval on which solution is computed:

tspan =[0,20];

%% Solve the system using |ode45| procedure:

[t,z] = ode45(’ode3’,tspan,z0);

%% Extract the positions and velocities:

x=z(:,1); v=z(:,2);

%% Plots of the positions and velocities as functions of time:

% *Note:* _The dashed curve indicates velocities_

plot(t,x,t,v,’--’)

%% Plot of the phase portrait (velocity as the function of position):

figure(2)

plot(x,v)

Save the script in ex2_script.m file (remember to place it in the working directory of Matlab) and try it

out. Alternatively, you can also download it from:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex2_script.m

Publish it using the Matlab command:

Page 72

72 JACEK POLEWCZAK

>> publish(’ex2_script’)

and view it with the command:

>> open html/ex2_script.html

And here is the link to ex2_script.html file:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex2_script.html

Finally, the output generated by publish(’ex2_script’,’latex’) and converted topdf file can be found

here:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex2_script.pdf

19. How to Download the Matlab Files Used in this Tutorial

The Matlab files created and used in this tutorial can be downloaded from:

http://www.csun.edu/~hcmth008/matlab_tutorial/

Department of Mathematics, CSUN

E-mail address: [email protected]

A VERY BASIC MATLAB PRIMER

JACEK POLEWCZAK

Contents

1. A Few Elementary Calculations 2

2. Finding Help in Matlab 2

3. Working with Arrays of Numbers 3

4. Creating Script Files and Simple Plots 4

5. Creating and Executing a Function File 5

6. Saving/Loading Data, Recording a Session, Clearing Variables, and More on Plotting 7

7. Matrices and Vectors 8

7.1. Appending or Deleting a Row or Column 10

7.2. Matrix Operations 11

7.3. Array Operations 12

7.4. Matrix Functions 13

8. Character Strings 14

8.1. eval Function 15

9. for and while Loops and if Conditionals 16

10. Interactive Input 18

11. Input/Output Commands 19

12. Linear Algebra 23

12.1. Solving Linear Square Systems 23

12.2. Gaussian Elimination 25

12.3. Inverses, Determinants, and Cramer’s Rule 26

12.4. Pseudoinverses or Generalized Inverses 28

12.5. Underdetermined and Overdetermined Linear Systems 29

12.6. Finding Eigenvalues and Eigenvectors 35

12.7. Generalized Eigenvectors 38

12.8. Matrix Factorizations, Matrix Powers and Exponentials 41

12.9. Characteristic Polynomial of a Matrix and Cayley-Hamilton Theorem 46

13. Curve Fitting and Interpolation 47

13.1. Hands-on Understanding of Curve Fitting Using Polynomial Functions 48

13.2. Interpolation 49

14. Solving Nonlinear Algebraic Equations 50

15. Numerical Integration - Quadrature 51

15.1. Quadrature For Double Integrals 52

16. Solving Ordinary Differential Equations 52

Date: Last updated November 2009.

Some of the examples in this tutorial are the modified versions of the items from Rudra Pratap’s, Getting started with Matlab,

Oxford University Press, 2002.

1

Page 2

2 JACEK POLEWCZAK

16.1. Solving Linear Systems of First Order Differential Equations 57

16.2. Linearization of a Double Pendulum 65

17. Use of Global Variables 68

18. Publishing Documents and Opening Web Pages in Matlab 69

19. How to Download the Matlab Files Used in this Tutorial 72

1. A Few Elementary Calculations

>> 2+4

ans =

6

Enter 2 + 4 and hit return/enter key.

>> x = 2+5

ans =

7

Assigning the value of an expression to a variable.

>> z= 3^4+log(pi)*cos(x);

>> z

81.8630

A semicolon suppresses screen output. You can re-

call the value of z by typing z

>> format short e

>> z

z =

8.1863e+01

The floating point output display is controlled by

the format command.

>> format long

>> z

z =

81.863014441556018

>> format short

>> z

z =

81.8630

>> quit Quit Matlab. Alternatively you can type exit com-

mand or select Exit Matlab from the File Menu.

For additional help type in Matlab: help format

2. Finding Help in Matlab

There are several ways to get help in Matlab:

• help functionname provides direct on-line help on the function whose eaxct name you know. For

example help help provides help on the function help.

• lookfor keyword provides a list functions with the string keyword in their description. For example,

>> lookfor prime

isprime - True for prime numbers.

factor - Prime factors.

primes - Generate list of prime numbers.

By clicking on isprime, factor, or primes additional help on those functions will be listed.

Page 36

36 JACEK POLEWCZAK

Also by checking

>> format rat; det(V)

ans =

-1121/1189

we observe that V−1 exists, with the property

>> format rat; V*D*inv(V)

ans =

8 1 6

3 5 7

4 9 2

>> A=magic(3)

A =

8 1 6

3 5 7

4 9 2

Thus, we have A = VDV−1. Furthermore, V−1AV =

D. Because of this last property, we say that the ma-

trix A is diagonalizable.

The eigenvalues and eigenvectors can be complex valued as the next example shows:

>> A=[0 -6 -1;6 2 -16;-5 20 -10]

A =

0 -6 -1

6 2 -16

-5 20 -10

>> format rat; [V,D]=eig(A)

V =

-383/460 899/4489 - 387/2777i 899/4489 + 387/2777i

-1071/3014 -753/3568 - 519/805i -753/3568 + 519/805i

-489/1151 -1736/2505 -1736/2505

D =

-2294/747 0 0

0 -1841/747 + 4277/243i 0

0 0 -1841/747 - 4277/243i

Not every n × n matrix A has n linearly independent eigenvectors. For example, it is easy to show that

matrix A =

[

0 1

0 0

]

has a double eigenvalue λ = 0 and only one eigenvector v =

[

1

0

]

.

One can prove that if n × n matrix A has n distinct eigenvalues λ1, λ2, . . . , λn, then A has n linearly

independent eigenvectors: K1, K2, . . . ,Kn. Furthermore, if V denotes n × n matrix whose columns are

eigenvectors K1, K2, . . . ,Kn, then

A = VDV−1 and D = V−1AV, where D =

λ1 0 · · · 0

0 λ2 · · · 0

...

...

0 0 · · · λn

Because of the identity V−1AV = D, we say that the matrix A is diagonalizable. An important class of

diagonalizable matrices are square symmetric matrices whose entries are real. A square matrix A is symmetric

if it is equal to its transpose, i.e., A = A′. In other words, if for A = (aij)i,j=1,2,...,n , we have aij = aji, for

i, j = 1, 2, . . . , n.

A matrix with repeated eigenvalues may still have a full set of linearly independent vectors, as the next

example shows:

Page 37

MATLAB PRIMER 37

>> A=[1 -2 2;-2 1 -2;2 -2 1]

A =

1 -2 2

-2 1 -2

2 -2 1

>> format rat; [V,D]=eig(A)

V =

-247/398 1145/2158 780/1351

279/1870 1343/1673 -780/1351

1040/1351 1013/3722 780/1351

D =

-1 0 0

0 -1 0

0 0 5

Matrix A has eigenvalues λ1 = λ2 = −1 and λ3 = 5.

A more readable expressions for the eigenvectors can be obtained by entering the command [P,J]=jordan(A)

(see Section 12.8.5 for more information on Jordan decomposition):

>> format rat; [P,J]=jordan(A)

P =

2/3 1/3 -1

1/3 -1/3 0

-1/3 1/3 1

J =

-1 0 0

0 5 0

0 0 -1

The columns of P represent the eigenvectors of A. Furthermore, after taking into account that eigenvectors

are determined up to multiplicative scalars, here are the eigenvalues and the corresponding eigenvectors:

λ1 = −1, K1 =

[

2

1

−1

]

; λ2 = 5, K2 =

[

1

−1

1

]

; λ2 = −1, K3 =

[

−1

0

1

]

.

As verified below, the first two columns of V (i.e., the eigenvectors corresponding to the repeated eigenvalue

−1) can be expressed as the linear combinations of the eigenvectors K1 and K3 :

>> format rat; [3*P(:,1) P(:,3)]\V(:,1)

ans =

279/1870 % c1

624/679 % c2

>> format rat; [3*P(:,1) P(:,3)]\V(:,2)

ans =

1343/1673 % c1

947/881 % c2

Consider the following non diagonalizable matrix:

Page 71

MATLAB PRIMER 71

As before, save the script in ex1_script_improved.m file (remember to place it in the working directory of

Matlab) and try it out. Alternatively, you can also download it from:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex1_script_improved.m

Once the Matlab script is running and placed in the current working directory of Matlab, you can publish it

using the following Matlab command:

>> publish(’ex1_script_improved’)

ex1_script_improved.html file will be created in html sub-directory of your current working directory.

You can view this newly created ex1_script_improved.html file in Matlab’s internal browser with the

command:

>> open html/ex1_script_improved.html

And here is the link to ex1_script_improved.html file:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex1_script_improved.html

After typesetting the LATEX file publish(’ex1_script_improved’,’latex’), its pdf output can be found

here:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex1_script_improved.pdf

The last example publishes the script in Example 3 of Section 16. The script uses an additional function file

ode3.m that can be downloaded from

http://www.csun.edu/~hcmth008/matlab_tutorial/ode3.m

and placed in the working Matlab directory.

Here is the corresponding Matlab script:

%% Nonlinear pendulum

%% The differential equation:

% $$\ddot{\theta}+\omega^2\sin\theta=0,\qquad \theta(0)=0,\qquad \dot{\theta}(0)=1.$$

%% The corresponding system of the first order differential equations:

% $$\frac{dz_1}{dt}=z_2,\,\,\frac{dz_2}{dt}=-\omega^2\sin(z_1),\,\, z_1(0)=0,\,\, z_2(0)=1.$$

%% Input initial conditions:

z0=[0,1];

%% Define the interval on which solution is computed:

tspan =[0,20];

%% Solve the system using |ode45| procedure:

[t,z] = ode45(’ode3’,tspan,z0);

%% Extract the positions and velocities:

x=z(:,1); v=z(:,2);

%% Plots of the positions and velocities as functions of time:

% *Note:* _The dashed curve indicates velocities_

plot(t,x,t,v,’--’)

%% Plot of the phase portrait (velocity as the function of position):

figure(2)

plot(x,v)

Save the script in ex2_script.m file (remember to place it in the working directory of Matlab) and try it

out. Alternatively, you can also download it from:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex2_script.m

Publish it using the Matlab command:

Page 72

72 JACEK POLEWCZAK

>> publish(’ex2_script’)

and view it with the command:

>> open html/ex2_script.html

And here is the link to ex2_script.html file:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex2_script.html

Finally, the output generated by publish(’ex2_script’,’latex’) and converted topdf file can be found

here:

http://www.csun.edu/~hcmth008/matlab_tutorial/solved_problems/ex2_script.pdf

19. How to Download the Matlab Files Used in this Tutorial

The Matlab files created and used in this tutorial can be downloaded from:

http://www.csun.edu/~hcmth008/matlab_tutorial/

Department of Mathematics, CSUN

E-mail address: [email protected]