Docsity

MATLAB Workshop - Academic Computing Support | BMED 8813, Lab Reports of Biology

Toggle sidebar
bg1
MATLAB workshop
DEAS IT: Academic Computing Support
16th February 2004
Spring 2004
Contents
1 Introduction to Matlab c
3
1.1 What Is MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 The MATLAB System . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Starting and stopping MATLAB . . . . . . . . . . . . . . . . . . 4
1.4 Basic MATLAB syntax . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Where to get help . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2 MATLAB Desktop and Examples 7
2.1 MATLAB Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Solution of linear system . . . . . . . . . . . . . . . . . . . . . . . 9
2.3 Solution of linear differential system . . . . . . . . . . . . . . . . 12
2.4 Fourier series analysis . . . . . . . . . . . . . . . . . . . . . . . . 14
2.5 Taylor series expansion . . . . . . . . . . . . . . . . . . . . . . . . 17
3 Matrices and vectors 20
3.1 Transpose of matrices and vectors . . . . . . . . . . . . . . . . . 21
3.2 Creating vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3 Creating matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.4 Basic matrix operations . . . . . . . . . . . . . . . . . . . . . . . 24
3.5 Indexing into a matrix . . . . . . . . . . . . . . . . . . . . . . . . 25
4 Graphics 27
4.1 2-D plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.2 3-D plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f

Partial preview of the text

Download MATLAB Workshop - Academic Computing Support | BMED 8813 and more Lab Reports Biology in PDF only on Docsity!

MATLAB workshop

 - 16th February DEAS IT: Academic Computing Support - Spring 
  • 1 Introduction to Matlab ©c Contents
    • 1.1 What Is MATLAB?
    • 1.2 The MATLAB System
    • 1.3 Starting and stopping MATLAB
    • 1.4 Basic MATLAB syntax
    • 1.5 Where to get help
  • 2 MATLAB Desktop and Examples
    • 2.1 MATLAB Desktop
    • 2.2 Solution of linear system
    • 2.3 Solution of linear differential system
    • 2.4 Fourier series analysis
    • 2.5 Taylor series expansion
  • 3 Matrices and vectors
    • 3.1 Transpose of matrices and vectors
    • 3.2 Creating vectors
    • 3.3 Creating matrices
    • 3.4 Basic matrix operations
    • 3.5 Indexing into a matrix
  • 4 Graphics
    • 4.1 2-D plots
    • 4.2 3-D plots
    • 4.3 Tables
  • 5 Programming with MATLAB
    • 5.1 Using m-files
    • 5.2 Scripts
    • 5.3 Functions
    • 5.4 Program flow control
  • 6 MATLAB workspace and File I/O
    • 6.1 MATLAB workspace
    • 6.2 Function workspace
    • 6.3 Native data files
    • 6.4 Data import and export
  • 7 Ordinary Differential Equations - cients 7.1 Second order homogeneous linear equation with constant coeffi-
    • 7.2 Non-homogeneous 2nd order differential equations
  • 8 Sparse Matrices
    • 8.1 Storage of data
    • 8.2 Creating sparse matrices
    • 8.3 Viewing sparse matrices
    • 8.4 Sparse matrix computations
    • 8.5 Reordering of matrices
  • 9 Numerical solutions of Ordinary Differential Equations
  • 10 SIMULINK
    • 10.1 Getting Started in Simulink
    • 10.2 Block Diagram Construction
    • 10.3 General Simulink Tips
    • 10.4 More information

structures etc. This component is particularly useful when writing scripts and functions to run in a non-interactive mode. The final component in MATLAB is the Application Programming Interface, otherwise known as the API. This allows users to extend MATLAB by writing specialized functions and methods in other high-level languages like C/C++ or Fortran. We will not be using this component in this workshop.

1.3 Starting and stopping MATLAB

  • On Windows platforms, to start MATLAB, double-click the MATLAB shortcut icon on your Windows desktop.
  • On UNIX platforms, to start MATLAB, type matlab at the operating system prompt.
  • On Mac OS X, start MATLAB by double-clicking the LaunchMATLAB icon in Applications.

You can change the directory in which MATLAB starts, define startup options including running a script upon startup, and reduce startup time in some situ- ations. To end your MATLAB session, select Exit MATLAB from the File menu in the desktop, or type quit in the Command Window. To execute specified functions each time MATLAB quits, such as saving the workspace, you can create and run a finish .m script. On Unix platforms typing matlab -h will give a listing of command line options that allow control over how MATLAB is opened. On a Mac OS X use:

/Applications/MATLAB6p5/bin/matlab -h

The ones of greatest use are -nodesktop -nojvm -nosplash. If you are using MATLAB by connecting to a remote unix machine with either a poor connection or no X windows support, this will launch a bare bones MATLAB environment that runs a lot faster than the one with the full graphical user interface support. Note that on a Mac OS X machine it is possible to get this brief version of MATLAB by typing

/Applications/MATLAB6p5/bin/matlab -nodesktop -nosplash -nojvm

(this assumes that MATLAB was installed in the default location of the disk). NOTE: MATLAB on Mac OS X will start X11 before starting MATLAB. It is very important that the X11 application stay running for the entire duration MATLAB is running. If the X11 application is closed before MATLAB is quit, you will not be able to run MATLAB any further and will have to shut it down.

1.4 Basic MATLAB syntax

MATLAB requires that all variable names be assigned numerical values prior to being used. Typing the name (say x), then the equal to sign (=), followed by

the numerical value (viz. 5 ) and finally Enter assigns the numerical value to the variable (in our example 5 is assigned to x). For example:

p=7. p =

A semicolon at the end of the expression typed by the user suppresses the system’s echoing of entered data

p=7.1;

It is also possible to combine expressions with a semicolon sign or a comma sign. Depending on whether a semicolon or a comma is used different things are echoed by the system.

p=7.1; x=4.92; p=7.1, x=4.92; p =

p=7.1, x=4.92, p =

x =

p=7.1; x=4.92, x =

The arithmetic operators in MATLAB are addition (+), subtraction (-), mul- tiplication (*), division (/) and exponentiation (^). For example the equation below:

t =

1 + px

)k

is written in MATLAB as:

t = (1/(1+p*x))^k

Some useful keys to remember are:

  • The ↑ key scrolls through previously typed commands. To recall a partic- ular entry from the history, type the first few letters of the entry and then press the ↑ key.
  • The ← and → keys allow you to edit the previously typed command
  • The ESC key clears the command line.
  • Ctrl+C quits the current operation and returns control to the command line.

2 MATLAB Desktop and Examples

2.1 MATLAB Desktop

When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications asso- ciated with MATLAB. The first time MATLAB starts, the desktop appears as shown in the Figure

Figure 1: The MATLAB desktop

You can change the way your desktop looks by opening, closing, moving, and resizing the tools in it. Use the View menu (see Figure 2) to open or close the tools.

Figure 2: The MATLAB desktop: View menu

You can also move tools outside the desktop or move them back into the desktop (docking), see the Figure 3. Note that these screenshots are from a linux machine. They may look dif- ferent in a Mac OS X machine or a Windows machine. In particular on a Mac OS X machine the File, View, etc. menu is not at the top of the MATLAB desktop but (like all other Mac OS X applications) at the top of the screen, as is shown in the Figure 4. On a Windows XP machine the MATLAB desktop looks as in Figure 5. You can specify certain characteristics for the desktop tools by selecting Preferences from the File menu. For example, you can specify the font char- acteristics for Command Window text. For more information, click the Help button in the Preferences dialog box. In addition to the File menu at the top MATLAB also has a Start button at the bottom left corner, that has shortcuts to some commonly used activities as shown in Figure 6

Figure 4: The MATLAB desktop: Mac OS X

and

x =

x 1 x 2 .. . xn

& b =

b 1 b 2 .. . bn

The symbolic solution is:

A−^1 Ax = A−^1 b dividing both sides by A−^1 x = A−^1 b

since A−^1 A = I and Ix = x, where I is the identity matrix:

I =

In MATLAB A\b is equivalent to inv(A)b (where inv(A) calculates the inverse of the matrix A) but it is calculated without inverting A. This results in a significantly reduced computational effort and time. So in MATLAB the way to solve this set of equations is as simple as x = A\b! An example of a linear system is the following set of equations: 8 x 1 + x 2 = 7 3 x 1 + 5x 2 = 4 In this case the matrix A is: ( 8 1 3 5

Figure 5: The MATLAB desktop: Windows XP

Clearly the determinant of A is 37, and so the inverse of A is:

1 37

The solution then becomes:

1 37

If we solve the same problem in MATLAB

A=[8 1; 3 5]; b=[7 4]’; x=A\b x =

we can confirm that we get the same answer with considerably greater facility of use. It can be confirmed that x is the solution of the equations, by multiplying it with A

z=A*x z = 7 4

yprime=FunctionName(t, g, p1, p2, ...) where t is the independant vari- able, g is the vector representing yj , and p1, p2, etc. are parameters. Consider the following second order ordinary differential equation, which could represent a forced damped oscillator.

d^2 y dt^2

  • 2ξ

dy dt

  • y = h(t)

Let us now make the substitution,

y 1 = y

y 2 = dy dt

Then the second order equation can be replaced by two first order equations. Assume that ξ = 0.15 and that we start at time t 0 = 0 and end at tf = 35. At t 0 the displacement and the velocity are both zero, viz. y 1 (t 0 ) = 0 and y 2 (t 0 ) = 0. Finally we assume h(t) = 1. First create the function which returns the array of right hand side functions (in this case a two element column vector.

function ForcingFunction(t, w, xi) % ForcingFunction - return the right hand side of the linear differential system % H1 line % ForcingFunction takes in the time t, vector w, and the constant xi. The % vector w gives the values of the dependant variable at the current time. y = [w(2); -2xiw(2)-w(1)+1];

save this as a file ForcingFunction.m. This file may be created using MAT- LAB’s own editor as displayed in the Figure 7.

Figure 7: Matlab’s built in editor

Then run the following commands:

[tt, yy] = ode45(@ForcingFunction, [0 35], [0 0]’, [], 0.15); plot(tt, yy(:, 1)) xlabel(’Time’); ylabel(’y(Time)’);

You should get the Figure 8 displaying the displacement y(t) of the oscillator with time t. As expected, the asymptotic value is the forcing value of 1, and the oscillator displays a transient with a damping related to the constant.

(^00 5 10 15 20 25 30 )

1

Time

y(Time)

Figure 8: Solution of the differential system

2.4 Fourier series analysis

Any real valued periodic function f (x)can be represented as an infinite sum of a Fourier series, a sum of sin and cos functions:

f (x) =

∑^ ∞

n=

an sin(nx) +

∑^ ∞

n=

bn cos(nx)

We can use the orthogonality properties of sin and cos to get the following

x=0:0.1:5*pi; p1=plot(x, mysquare(x, 1), ’k’); hold on p2=plot(x, fouriersquare(x, 1, 10), ’r’); p3=plot(x, fouriersquare(x, 1, 50), ’b’); p4=plot(x, fouriersquare(x, 1, 200), ’g’); legend([p1, p2, p3, p4], ’Exact’, ’n=10’, ’n=50’, ’n=200’); xlabel(’\theta’) ylabel(’f(\theta)’) title(’Fourier fitting square wave’)

−0.2 0 2 4 6 8 10 12 14 16

0

1

θ

f(θ )

Fourier fitting square wave Exact n= n= n=

Figure 9: Fourier series fit of the square wave

As can be seen the fit gets closer as the number of terms increases, but there remains even in the sums with very high numbers of Fourier terms a ringing near the edges of the square wave. This is a well known phenomenon and can be understood as a natural problem occuring from trying to fit a function with a discontinuous derivative with a sum of trignometric functions all of whose higher derivative are continuous.

2.5 Taylor series expansion

Most well-behaved functions (viz. possessing derivatives of any order) can be expressed as a polynomial series expansion about some location:

f (x) =

∑^ ∞

n=

f (n)(a) n! (x − a)n

In the above f (n)^ is the nth^ order derivative of f (x), i.e.:

f (n)(x) = dnf (x) dxn

and n! is of course the factorial n(n − 1).(n − 2)... 2 .1 of n. This is known as the Taylor’s series expansion. Consider for example the sin(x). This can be expanded about x = 0 as:

sin(x) = x −

x^3 3!

x^5 5!

x^7 7!

This result can be easily derived if one recalls that all even derivatives of sin(x) will some power of − 1 × sin(x) and so must vanish at x = 0. And all odd derivatives of sin(x) will be some power of − 1 × cos(x) which will be equal to 1 (or −1) at x = 0. We can then use Matlab to create a function to calculate the series for a given number of terms n. The function taylorsine (in the file taylorsine.m) is

function y=taylorsine(x, n) % taylorsine - Calculates the taylor series approximation to the sine function % H1 line % taylorsine takes in the value of x and number n of terms to sum to and % returns the value of the fit y sum = 0; for m=1:2:n; % pick each odd term to n sign=(-1)^((m-1)/2); % sign of each term yterm = sign*x.^m/factorial(m); sum = sum + yterm; end y=sum; return

Then the following series of commands on MATLAB

x=1:1:15; format long for i=1:1: y(i)=taylorsine(pi/4,i); ex(i)=sin(pi/4); end hold off

p15=plot(x, y15, ’kx’); xlabel(’\theta’); ylabel(’sin(\theta)’); legend([p, p1, p2, p5, p15], ’Exact’, ’1 term’, ’2 terms’, ’5 terms’, ... ’15 terms’); title(’Taylors series fit of sin(\theta)’);

Note that we used the function taylorsine defined above to calculate the series fits for 5 terms and 15 terms. This results in the Figure 11.

−4 −4 −3 −2 −1 0 1 2 3 4

−

−

−

0

1

2

3

4

θ

sin(

θ)

Taylors series fit of sin(θ) Exact 1 term 2 terms 5 terms 15 terms

Figure 11: Taylor series expansion of Sin(θ)

As noticed before upto about 45◦^ the linear fit is quite good! After that the linear fit rises too quickly. Adding the second term (which is negative) bring downs the contribution of the linear term, but it does so too fast! Adding the next term brings up the fit to above the exact curve and so on until at about 15 terms the fit looks quite good between the ranges −π < θ < π.

3 Matrices and vectors

An array A of m rows and n columns is called a matrix of order (m × n). The elements of A are referred to as Aij where i is the row number and j is the column number. The simplest way of entering the matrix in MATLAB is by entering it explicitly. To enter the matrix, simply type in the Command Window

A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1

The order of the matrix A is determined with:

size(A) ans = 4 4

Note that the function size returns two values. It is possible to assign these values to variables as follows:

[m, n] = size(A) m = 4 n = 4

Note that to enter the matrix as a list of its elements you only have to follow a few basic conventions:

  • Separate the elements of a row with spaces or commas.
  • Use a semicolon, ;, to indicate the end of each row.
  • Surround the entire list of elements with square brackets, [ ].

It is possible to mix spaces and commas when declaring a matrix as shown below

A = [16, 3, 2, 13; 5, 10 11, 8; 9, 6 7, 12; 4, 15, 14 1] A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1

But this can get very hard to read. Vectors are just a special case of matrices. If m = 1, then A is a column vector. Similarly if n = 1 then A is a row vector.