Matlab-intro

advertisement

1

MATLAB

An Introduction

By: Salim

Other resources used in the development of this document are:

-

-

Learning MATLAB

®

Mastering MATLAB

7

” by the MathWorks

®

6 – A comprehensive Tutorial and Reference

” by

Duane Hanselman, Prentice Hall.

All students are HIGHLY encouraged to buy their own latest release of the Student

Version of Matlab & Simulink found at: http://www.mathworks.com

Important:

SAVE ALL OF THE files asked for in the document. The instructor may ask at anytime to view some or all of the files and may ask the student to explain how these

Matlab commands in those files work.

DO NOT PRINT the document. It is a long document.

Complete all items in this handout. Once each item is completed, check the box at the end of the corresponding item

Preface

The purpose of this document is to give the students an exposure to Matlab. Matlab is a powerful technical computing environment, therefore, many of its features will be taught as the need arises. Students are highly encouraged to go through the manuals provided with the student edition and to refer to the Matlab documentation. In addition, visit the

Mathworks web site for additional information.

Again, the following information is geared towards – “getting started.”

What is Matlab?

“MATLAB is a high-level language and interactive environment that enables one to perform computationally intensive tasks faster than with traditional programming languages such as C, C++, and Fortran.”

“You can use MATLAB in a wide range of applications, including signal and image processing, communications, control design, test and measurement, financial modeling and analysis, and computational biology. Add-on toolboxes (collections of specialpurpose MATLAB functions, available separately) extend the MATLAB environment to solve particular classes of problems in these application areas.

MATLAB provides a number of features for documenting and sharing your work. You

can integrate your MATLAB code with other languages and applications, and distribute your MATLAB algorithms and applications.

Key Features

-High-level language for technical computing

-Development environment for managing code, files, and data

-Interactive tools for iterative exploration, design, and problem solving

-Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, and numerical integration

-2-D and 3-D graphics functions for visualizing data

-Tools for building custom graphical user interfaces

-Functions for integrating MATLAB based algorithms with external applications and languages, such as C, C++, Fortran, Java, COM, and Microsoft Excel “

Source: The Mathworks.com

All data in Matlab are stored as arrays, thus Matrices, vectors and arrays are, generally, the fundamental core of Matlab.

Features Explained in This Documents:

ABasic Features a.

Mathematical operations – simple b.

Matlab environment c.

Variables d.

Numeric data types e.

Comments f.

Standard math functions

BMatlab Path and files a.

Managing files b.

Hierarchy and Matlab search path c.

M -files

CArrays and Matrices a.

Arrays indexing b.

Array manipulations c.

Array mathematics d.

Sorting e.

Factorization f.

Appending, truncating, split, reverse, pad, etc.

DCharacter Strings a.

String functions b.

String to number, number to string c.

String evaluation

EOperators a.

Mathematical b.

Relational c.

Logical

2

FControl Flow a.

For loop b.

While loops c.

Conditional d.

Switch e.

Try-catch

GFunctions and function call a.

Creating own functions b.

Creating own toolbox c.

Function evaluation

HTime functions

IMatrix Algebra

Ja.

Linear Equations b.

Matrix functions c.

Relation to LTI systems

Data Analysis and Interpolation a.

Data analysis b.

Statistical functions c.

1-D and 2-D interpolation

KPolynomials a.

Roots b.

Operations

LMathematics a.

Linear and nonlinear differential equations b.

Initial value problems c.

Boundary value problems d.

Integration e.

Differentiation

MGraphics a.

1-D plots b.

1-D subplots / multiple plots c.

2-D plots d.

3-D plots (mesh, surface, contour plots)

NData Files

OGUI

PControl Design Toolbox

QSymbolic Toolbox

3

This document is written as an interactive discovery. Students will answer questions as they arise. Read all parts of this document – make sure you explore all items listed and beyond. Matlab is very powerful – This document basically just a getting started lesson.

ABasic Features

When you start Matlab, typically three windows appear. The Command Window, the Current Directory/Workspace, Command History. The workspace keeps the commands and values of variables. As well, the size of each variable is kept in the workspace. You can modify (add or remove) display windows by selection

“desktop”>>”desktop layout” and checking/un checking options.

Exercise -1

Stat Matlab

In the command window, at the prompt, type the following:

>> a=5

>>b=6

>>c=12; (note : “ ;” was added here)

Notice how the inclusion of “;” suppresses printing.

>> d=a+b+c;

>>d

View the Workspace window for variables

At the command prompt, type the following:

>> who

>> whos

What is the difference in result? ------------------------------------------------------------------

Check this box when this exercise is completed

Arithmetic operators:

The typical operators are used:

+, -, *, ^ and

/

\

In the Matlab command window, try the following:

>> 12/5

>> 12\5

>>5/12

4

What does the symbol “\” do? ---------------------------

You may type help \ at the command prompt

The order of operations is consistent with the usual rules of operations.

Check this box when this exercise is completed

About Variables:

-

-

-

Variables are case sensitive

Variable names can contain up 31 characters (anything beyond is ignored)

Variable names must start with a letter followed by any number of letters, digits, or underscore.

Exceptions are Matlab reserved words such as: end, while, for, try, catch, switch, …

Special variables: ans beep pi default variable name used for result as the name implies inf

NaN i or j infinity not a number

1 nargin number of input arguments in a function nargout number of output arguments in a function realmin smallest positive floating point number realmax largest positive floating point number in the command prompt, type the following

>> help realmin

>>help varargin

>>help vararout

Check this box when this exercise is completed

Comments:

Comments are included by including the symbol “ % “

Type the following:

>>a = 5; % this is a

>>% the following is b

>> b =20;

5

Notice the color coding

Complex Numbers

We can write complex numbers as: a + bi or a+bj

Example:

Let us define two complex numbers and perform some simple mathematical operations:

Type the following

>>x=4 – 5j;

>>y=-2 + 8j; find the following: a) x+y = --------------------------- b) x-y = -------------------------- c) x/y = ---------------------------- d) magnitude of x = ---------------------------- (what command did you use?) ----------------- e) argument of x = -------------------------- (what command did you use?) ------------------------ f) complex conjugate of x = ------------------------------ (what did you use?) ----------

Check this box when this exercise is completed

Explore the following using help command: e.g., >>help abs (it is important to remember and understand these features.) abs angle float double single isfloat sint uint format complex cplxpair conj ceil

6

floor fix mod rem sqrt gcd lcm etc……

-

type who at the prompt clear one of the variables from the workspace (say a):

>> clear a

>>who notice , a is not in the list anymore

Clear all variables:

>> clear all

>>who (notice they are gone!)

Clear the command window screen

>> clc

Now, let us do the following:

>>a=10;

>>b=12;

>>c=a+b;

>>d=c/12

Suppose we want to change the value of a, we then have to use the up and down cursers to get to a, but we then have to execute every command that uses it in order again.

Change a to 50 and determine d: d = -------------------------- (re-run every command that follows (specially those that are directly or indirectly dependent on the variable a.)

Now, you can easily go back to a as follows:

At the prompt, type a and hit the up arrow !!! notice quick access …

Check this box when this exercise is completed

7

8

Explore format:

>>pi

>>format long

>>pi

>>format (sets back to default – same as format short)

>.>format short e

>>pi

>>help format

Explore this feature a bit.

>>format rat

>>pi

>>format

MATLAB provides information about the computer in use and about MATLAB itself and all the toolboxes installed.

Try these commands:

>>computer

>>version (this is for MATLAB version)

>>ver (this is about MATLAB and the toolboxes installed)

Check this box when this exercise is completed

BPath

MATLAB uses a search path to find information stored in files in numerous directories and subdirectories.. To list all the directories where the MATLAB files are found type the command:

>>matlabpath or

>>path

Important:

Use of MATLAB search is described by the following:

When you enter a command (assume hello ) at the prompt ( a command to run an instruction , or a command to execute a file name, ... or whatever) MATLAB does the following: aIt checks to see if hello is a variable in the MATLAB workspace bit checks to see if hello is a built in function

cit checks if a filename hello.m

exists in the current directory. dit checks to see if hello exists anywhere in the MATLAB search path eif not found, an error is reported.

NEVER alter any of the MATLAB files. All of your work MUST be done in a separate directory. You can always access and call the different Matlab functions … NEVER alter them .

Create a folder on the N drive and call it MLWORK

Add this folder to the MATLAB search path. To do this, follow these instructions:

in the MATLAB command window, go to file /set path/ add folder

follow the instructions on the screen (do not forget to click save on the add path window.)

Check this box when this exercise is completed

Script M-Files

As the number of commands increase, it becomes tedious to input the commands at the

Matlab command window. The solution is made easy with Matlab: create a text files and enter your Matlab commands in it (MATLAB program file.) Save the file as a .m

file, e.g. hello.m (This step is explained in the following practice exercise.)

First, make sure the folder creation step above is completed! \

In the Matlab desktop, select: file>new>m-file

Type the following code

% This is program number -1

% getting to know m-files a=10;b=20;c=30;

% x=2;

% let the value of y be user input

% the following statement is echoed to the screen disp(' Please enter a number for y') %notice I did not use “;” why?

y=input('the value of y = ') disp(' ---------------') disp(' The result is') disp(' hit any key to continue') pause%

W=a+b+c/x+y

Select file>save as> (navigate to MLWORK directory) and type the file name hello.m

9

Check this box when this exercise is completed

(You can run /debug from the editor window, however for now, go to the Matlab command window and at the prompt, type the file name:

>>hello notice how the file runs … now, it is easy to modify and run again … explore pause , pause(5) , etc .. in the hello.m program.

In the command window, do the following:

>>echo on

>>hello

What do you notice ?

>> echo off

>>hello

>>help keyboard

>>help return

What do these two commands do? (useful for debugging)

Check this box when this exercise is completed

CArrays and Matrices

Recall, arrays and matrices are the core of Matlab --- thus we need to explore/ discover some of the features … This topic will be dealt with in greater details throughout the course.

[ ] are used for arrays and matrices… the 1-D row array x can be entered as:

>>x=[1,2,4,5] or

>>x=[1 2 4 5] This is the form I personally prefer to use …

>>y=[1;2;4;5] this defines a Column vector notice the use of

;

10

Check this box when this exercise is completed

Let us write a .m file to explore some of the array operations:

In Matlab command window, file>new file>m-file

Type the following: clear all echo on

% on 1-D arrays

% let us suppose we have the following:

% x = { 1,4,6,10,20} and

% y = 20*x+5

% then x=[1 4 6 10 20]; % this is how the array is entered y=20*x+5; file>save as> hello2.m

Now, in the Matlab command window do the following:

>>hello2

>>x

>>y

>>size(x)

>>length(y)

What does the result of size mean? ------------------------------------------

What does the result of length mean? ---------------------------------------

Check this box when this exercise is completed

>>g=x’;

>>g

What is the dimension of g? -----------------------------------

What is the mathematical meaning of ‘ in g=x’ ? -----------------

We can index elements:

>>x(3)

We can modify elements of an array:

11

>>y

>>y(2)=1000;

>>y

We can list a range of elements:

>>x(2:4)

What does the above do? -------------------------------------------------

>>x(3:-1:1)

What does the above do? ----------------------------------------

>>x(2:2:5)

What does the above do?

>>x(3:end)

>>y

>>y(5)

>>y([2 4 5])

What does the above do ? -----------------------------------------

>>[y(2) y(4) y(5)] %The previous one is simpler !!!

Check this box when this exercise is completed

Array Construction

Enter and explore the following:

Create a new .m file and type the following :

% More on 1-D arrays ... Array manipulations clear all clc echo off x=0:.2:2; y=sin(x); disp(' the 1-D arrays are: ') x y pause % disp('size of x and y vectors are:')

12

size(x) size(y) pause disp('let us change the orientation of array y and place the new vector in z') z=y' % this is the transpose command. disp(' size of vector z is:') size(z) pause disp('let us append vector x by 3 values, two more in the beginning and one at the end') disp('the original x is:') x pause disp('now the new x is:') x=[-2 -1 x 3]; %handy to know x disp('the size of this x is:') size(x) pause disp('let us change x back')

% the following use of : is handy to know x=x(:,3:end-1) % isn't this fun or what FYI: The first : indicates ALL rows .... pause save the file in the MLWORK folder as: hello3.m

In the command window, run the file.

Play with the above for a while

Check this box when this exercise is completed o To create a matrix: (look how the rows are separated by “;”)

>> g=[1 2 3;0 -1 -2;1 4 -8] g =

1 2 3

0 -1 -2

1 4 -8

>>h=[3 4 5;-1 4 9;-4 -6 1] h =

3 4 5

-1 4 9

-4 -6 1

See note at end of this example

13

In Matlab command window, perform each of the following commands. Make sure to make sense of the results.

You can perform the matrix operations (rules of linear algebra must hold):

g+h h-g -

-

-

-

2*g g*h h’ (transpose) element by element division: g. /h -

-

inv(g) (matrix inversion) rank(g) Matrix rank – among others, it gives an idea of number of linearly independent equations in a linear system

eig(g) eigenvalues of matrix g [think of it as roots of the

-

-

characteristic polynomial) size(g) w1=[g h]; w2=[g;h];

Note: I personally prefer to enter matrices as follows:

A =[1 2 3

4 7 9

3 -1 2];

This makes it easier to follow

Explore the following: o ones(3) o rand(4) o eye(8) Important identity matrix o check this out:

 a=[1 4 5];

 k=diag(a)

From our matrix g above (explore the following) o g(2:3) o g(2:3,:) o g(:,3) o g(2,1)+g(3,2) k=[ ] (this is a way of initializing an array as empty vector - null)

Check this box when this exercise is completed

14

DStrings

Consider:

>> t='welcome to Matlab --- ' t = welcome to Matlab ---

>> size(t) ans =

1 22

Let us see the ASCII behind this:

>>q=double(t)

Let us perform the inverse transformation:

>>M=char(q)

>>L=input('what is your name ','s') % run this command – you should get: what is your name Mike

L =

Mike

Run the following:

>> L=input('what is your name\n','s') run the following:

>> AA=char('Car','Truck','Apple','Orange')

>>help char for more info

There is a whole list of string functions - refer to the Matlab Documentation

Check this box when this exercise is completed

15

16

ERelational and Logical Operators a.

The typical < , > , < = , > = , = = , ~= b.

& , |, ~ (AND, OR, NOT) look at the simple code: Write the code in a Matlab file hello4.m and demonstrate to instructor (DO NOT COPY AND PASTE – you will miss out on something !!!) c.

x=2; if x>=3

y=6; else

y=7 end

Write the following in hello5.m and demonstrate to instructor (DO NOT COPY

AND PASTE – you will miss out on something !)

An example with logical operators: a=4;b=5; if(a==2 & b==5) r=20 else if a>1 disp(‘test1’) else disp(‘test2’) end r=30 end

Check this box when this exercise is completed

17

FControl flow

The typical loops (for and while), the if-else-end, and the switch case and try-catch instructions are explored here …

For loops:

Write the following in hello6.m

file and explore: clear all clc

% this program demonstrates the use of the for loop and

% how to build an array within a loop.

X=[] %initialize an empty (null) array

I=[] for i=1:6 % the default step size is 1

x=2*i^2 % no ";" is used to ensure that the value is displayed

X=[X x]

I=[I i]

disp(' hit any key to continue')

pause % end

As you run it, notice how the vectors are appended!

One can also use indexing (as you would have done with any other programming language.) I must note that I prefer the format of array building (above) since Matlab is a powerful vector and matrix tool.

Check this box when this exercise is completed

Example:

Type the following in hello6a.m

clear all clc

% this program demonstrates the use of the for loop

% and indexing for i=4:1:20 % here the step size is 1

x(i)=4*i^3; end disp(' the result is') x disp('notice x is a one row array - hit any key to continue') pause % size(x) disp('change x to one column array')

x=x'

Question:

Modify the step size in example hello6a.m to 2 ….

What observation do you make of the result? ----------------------------------------

----------------------

How can the code be corrected so that only intended elements of the array are printed?

Note: a for loop cannot be terminated by reassigning the loop variable within the for loop- example: name it hello7.m for i = 1:8

x(i) = 5*i;

i=8; end

>> x

Try the above and test the validity of the argument !

Check this box when this exercise is completed

Vectorization code:

Consider and Type the following nested loop – name it hello8.m

clear all clc

% this program demonstrates the use of nested loops

% and compares the result to the one obtained using a much

% faster and a more intiutive approach for m = 1:6 for n= 6:-1:1

X(m,n)=m^2+n^2; end end disp( ' The resulting X matrix is: - Hit any key to continue' )

X pause

% The equivalnet vectorized code is: (WILL USE DIFFERENT VARIABLES) i=1:6; j=1:6; disp( 'hit any key to continue' )

[H,K]=meshgrid(i,j) pause %

X=K.^2 + K.^2

18

19 disp( 'notice - same result -- no loops were directly used -- much faster and easier to use' )

Run the above code AFTER studying it

Check this box when this exercise is completed

Now, modify the line before last (indicated as boldface) in the code above by removing the dot “.” and run the program again ..

Explain the result:

What is the purpose of the dot “ .

” ?

Check this box when this exercise is completed

While Loops:

Here we will also demonstrate the use of eps (in Matlab command window, type: help eps to learn more about this.)

Creat hello9.m

file and run the following code – explore eps …. Very handy … clear all clc x = 0; eps=1; while (1+eps)>1

eps=eps/2

x=x+1; end disp('the loop ran x time ') x eps if-else-end statements:

Create a hello10.m file and write a code to do the following: [must use if-else-end ]

The pseudo code is:

Enter a value for X

If X > 10

Then Y =20

20

Else if X <3 then

Y=5

Else

Y =7

Print Y

Demonstrate a working program [using if-else – end statements] to instructor

Check this box when this exercise is completed

Switch – Case

Type help case and help switch

Create hello11.m

and run the following:

STUDY the code and understand how to use the switch statement in Matlab well. clear all clc x=3; units='cm'; switch units

case {'inch','in'}

y=x*2.54;

case {'meters','m'}

y=x/100;

case {'centimeters','cm'}

y=x;

otherwise

disp([unknown units',units])

y=NaN; end y modify the value for units and run again..

Check this box when this exercise is completed

Try-Catch-Block

This is to have user control for error trapping. With this command, errors that are found by Matlab are captured and thus the user has the ability to control how Matlab responds to errors.

Create hello12.m

and test the following code

21 clear all clc

x =ones(2,3); y=eye(2); try z=x*y % of course: this is illegal operation (dimension mismatch) catch z=nan; disp('x and y are not of appropriate dimensions') end z

Check this box when this exercise is completed

Now, comment the lines try and catch and run the program again ..

What is your observation? --------------------------------------------------------------------------

Check this box when this exercise is completed

Command Menu:

Type the following example and become familiar with it…

Create the file hello13.m

and run the following program – disp(' This is an example of the menu command') disp(' Enter your choice\n')

W = menu('Enter your choice for operatin','Step Response','Impulse Response','Frequency Response'); switch (W)

case 1

disp(' You chose the step response')

pause(3)

case 2

disp(' you choose impulse response')

case 3

disp('You choose the freq. Response')

otherwise

disp('error- choose one')

end

Check this box when this exercise is completed

G- Function Calls

22

This is a nice and a very useful feature.

The purpose of this portion of the lab is to create a function that will allow us to perform an operation and use in future programs. Function calls and local and global variable concepts that we learned in C apply here too.

The operation I chose is:

Create a function that will calculate the closed loop transfer function of a negative feedback system and find the roots of the characteristic polynomial.

Display the results

Procedure:

create a new matlab file ( .m) file and write the following into it (This is the function.): myfunction.m function [a,b,c,d]=myfunction(n1,d1,n2,d2)

% this function has four input arguments

% the input arguments are num1, den1, num2, den2

% where num1,den1 are those for G(s) and num2,den2 are for H(s)

% the function returns four arguments (you may choose however many you

% want)

% the output arguments in order are:

% Numerator of the closed loop system

% denominator of the closed loop system

% transfer function of the closed loop system

% the roots of the characteristic polynomial of the closed loop system

% the form is:

% [NUM,DEN,Gclosed,RootsCsd]=myfunction(numerator1,denominator1,numerator2,denominator2)

% You may choose any number of variables to be returned >0 .. the return is

% in the order specified in the function call disp(' ');

% error checking if nargin<4, error('not enough input arguments');end if nargout==0, error('need at least one output argument');end

G=tf(n1,d1);

H=tf(n2,d2); c=feedback(G,H);

[a,b]=tfdata(c,'v'); d=roots(b);

Save the file above in your working directory as myfunction.m

Now, let us call the function:

o in Matlab’s command window (not in a file), enter the following to define the polynomial coefficients:

>> num1=[1 0.5];

>> den1=[1 8 20];

>> num2=[1];

>>den2=[1 7];

>>help myfunction look at the help instructions …. ! This is the help you provide in the function itself. now, enter the following into the command window of Matlab

>>[Nu,De,Gcl,rts]=myfunction(num1,den1,num2,den2)

did the function call work as it was supposed to … ?

Examine each of the return arguments:

>>Nu

>>De

and so on ..

Check this box when this exercise is completed o Once all of the above is working fine, create a new Matlab file and place the following code in it. The file should be saved as a .m

file

Call the file hello14.m

% given a closed loop system with G and H transfer functions as

% follows, we are to use a function call to determine the closed loop

% transfer function and some of its characteristics. clear gnum=[1 2]; gden=[1 2 4]; hnum=[1]; hden=[1 1];

[num,den,Gcl,rootscl]=myfunction(gnum,gden,hnum,hden); disp('The returned variables are:') disp('closed loop coeffiecniets for the numerator and denominator are:\n') num pause(3) den pause(3) disp('the closed loop transfer function is:')

Gcl pause(3)

23

24 disp('the roots of the characteristic polynomial of the closed loop system are:') disp(' \n') rootscl pause( 3) o Run the program

Check this box when this exercise is completed

Question:

Modify the file myfunction.m

and save it as myfunc2.m

so that it accepts two input arguments and still returns up to four output arguments. That is, the function should, by default, assume that H(s) =1 if the input arguments are = 2 and not 4.

Demonstrate this result to the instructor

Check this box when this exercise is completed

HTime Functions:

At the command prompt

>>T1= clock

>>for i=1:100 end

>>T2=clock

>>D=T2-T1

At the command prompt

>>g=date

Check this out:

>>[Day_number, Day_name]=weekday(81235)

Type the following to see different options for the function call

>>help weekday

Type

>>help tic

>>help toc

Check this box when this exercise is completed

25

IMatrix Algebra (simple overview – since this topic is explored intensely in the course.)

Suppose we have the following system of equations:

A.x =b

1

7

2

4

1

8

9

1

3

 x x x

3

1

2

22

10

40

Solve for the vector x.

It is obvious that x

A

1 b

Well, let us do this using Matlab:

Create hello15.m

and save it in the MLWORK directory that you have created earlier.

Run the program. clear all clc

A=[1 4 -3;7 1 9;-2 -8 1]; % notice the ";" starts a new row.

% You can enter A matrix as follows if you wish (let us call it A1)

A1=[1 4 -3

7 1 9

2 -8 1];

B =[10;-40;22]; x=inv(A)*B inv gives the inverse of a matrix

“ * “ is the multiplication operator

Note: (Alternative )

One may use the left division operator to do the same thing as x=inv(A)*B x= A\B try this in the command window and verify the result. Does it work the same? --

--------

The notation “ ‘ “ gives matrix transpose A

T

In the command window, do the following:

>>A

>>A’

Did matrix A transpose work? ---------------- null orth pinv poly polyeig polyvalm qz rref schur sqrtm subspace trace funm svd gsvd hess logm lu norm

Check this box when this exercise is completed

Type help (for each of the following) – READ CAREFULLY cdf2rdf cond det eig expm

Check this box when this exercise is completed

26

JData Analysis

Suppose we have the vector :

V= 1 4 5 12 33 0 9

Find the mean of this vector

>>V=[1 4 5 12 33 0 9]

>>answer=mean(V)

>>Y=max(V) % this returns the max value

Try the following:

>>[Y,I]=max(V)

What does the above return? -------------------------------------------

Likewise for min command. Try it – does it work? ---------------------------

Try this:

>>diff(V)

What does it do? ------------------------------------------

>>sort(V) What does it do? -------------------------------

>>median(V)

>>help filter

>>filter(ones(1,4),4,V)

What does this do? --------------------------- (Think moving average)

Type help for each of the following commands – try some of them – useful corrcoef cov cplxpair cumtrapz prod trapz var

Check this box when this exercise is completed

27

Here is another example – different

Create a file hello17.m

, save it and run it --- Learn and enjoy clear all clc t=0:.002:.02; % a time vector y=sin(2*pi*100*t);

% look at the data in a 2-D vector format: disp(' the input and output data is') disp('Hit any key to continue') disp(''); disp(' t y')

[t' y'] pause

% now let us plot the data: disp('Hit any key to continue') plot(t,y,'+') title('plot -1 points- discrete') xlabel('time, sec.') ylabel('voltage, V') pause disp('a line plot- continuous') disp('Hit any key to continue') plot(t,y) title('plot -1 points- discrete') xlabel('time, sec.') ylabel('voltage, V') pause

% now, let us smooth the data (Interpolation Filter)

G=interp(y,3); plot(G) look at the plots as you run it and compare results.

Now, for the interp command, change the multiplier from 3 to 20. Do you notice any improvement in the interpolation filtering ? ---------------------------------

Check this box when this exercise is completed

28

29

Data Interpolation 1-D and 2-D interpolations

Let us create a sampled data list and plot it . Let us assume the data is time and temperature. Once that is completed, let us interpolate to determine the temperature and some – not given- time. Will use linear, cubic, cubic splines interpolations and nearest neighbor interpolations. Notice the default interpolation is linear (thus it does not have to be included in the command line)

Create a file hello16.m

and run it

clear all clc

t=[0 1 2 3 4 5 6 7 8 10 11];

Temp=[20 28 35 46 52 69 78 81 68 50 33]; plot(t,Temp,'o')

F1=interp1(t,Temp,4.5,'linear');

F2=interp1(t,Temp,4.5,'cubic');

F3=interp1(t,Temp,4.5,'spline');

F4=interp1(t,Temp,4.5,'nearest'); disp('liear, cubic, spline, nearest neighbor')

[F1 F2 F3 F4]

Run and observe results

Check this box when this exercise is completed

The above was 1-D interpolation- let us visit 2-D interpolation.

Let us create data for signal strength

Given x-axis, y-axis and the corresponding signal strength, plot the data and interpolate for some not provided points.

Note: added the commands: mesh and clf

Type help mesh and help clf

Create a file hello18.m

, save and run

Explore the interpolation at different values of x and y (However, instead of changing the values of x and y in the program, use the input command.) – Demonstrate to instructor. clear all clc clf x=0:0.5:3; y=0:.5:4;

z=[60 58 60 58 60 58 60

60 58 58 58 60 58 58

60 58 57 56 57 58 59

60 60 58 58 59 60 60

61 61 60 58 57 58 59

62 61 60 57 58 59 60

60 57 56 57 58 59 60

60 58 57 58 57 59 60

57 56 57 58 59 60 60]; disp('hit any key to continue') mesh(x,y,z) xlabel('x-Km') ylabel('y-Km') zlabel('sound level') title('interpolation example') pause

% now we can interpret for data within the rectangle

Z1=interp2(x,y,z,1.3,2.2,'linear');

Z2=interp2(x,y,z,1.3,2.2,'cubic');

Z3=interp2(x,y,z,1.3,2.2,'spline');

Z4=interp2(x,y,z,1.3,2.2,'nearest'); disp('interpolation at x=1.3 and y=2.2 is given by four different methods') disp(' linear cubic spline nearest')

[Z1 Z2 Z3 Z4]

Check this box when this exercise is completed

KPolynomials

Roots, product and division

Given the polynomial found as follows:

10 x

4 

5 x

3

>>P=[10 5 -3 2 20];

>>r=roots(P)

3 x

2 

2 x

20 , the roots of this polynomial are

We can also go from roots to polynomial:

Given the roots, r, the polynomial is found as follows:

>>P1=poly(r)

Check this box when this exercise is completed

30

Multiplication of polynomials:

Given the two polynomials, p1 and p2, their product result is given as follows: p 1 p 2

 x

2

7 x

3

1 x

2 ,

P1*P2 is calculated by using the convolution command (for more on convolution type

>>help conv

P3=conv(p1,p2)

Check this box when this exercise is completed

To verify:

Show that the union of the roots of p1 and p2 is equal to the roots of P3 Verify this answer and demonstrate to instructor ………………………………

Division:

When dividing, use the polynomial deconvolution

The result is returned in q and the remainder is returned in r

>> [q,r]=deconv(p1,p2)

Check this box when this exercise is completed

Curve Fitting:

Suppose we have data for x and y and want to plot using linear, quadratic, and higher order polynomials:

Create hello19.m

, save and run --- try different values for the order, n. clear all clc clf x=[0:.1:1]; y=[-0.45 1.98 3.28 6.20 7.1 7.35 7.67 9.60 9.45 9.31 12]; subplot(221) plot(x,y,'.') title('no fitting') subplot(222) plot(x,y) title('no fitting') p1=polyfit(x,y,1) % this gives a polynomal coefficients for the curve fitting equation

31

32 y1=polyval(p1,x) % calculates the y values using the curve fitting equation found above subplot(223) plot(x,y1,x,y,'*') title('linear - In this case this is no good') p3=polyfit(x,y,5) % this gives a polynomal coefficients for the curve fitting equation 5th order in this case y3=polyval(p3,x) % calculates the y values using the curve fitting equation found above subplot(224) plot(x,y3,x,y,'*') title('5th order polynomial fitting- much better')

Check this box when this exercise is completed

For more advanced knowledge of this:

1verify that higher order polynomials may cause problems (large errors)

2look at cubic splines --- good stuff

LMathematics

Numerical integration and differentiation:

The are three functions for numerical integration: quad, quadl and dblquad

Let us generate a vector of linearly spaced data points on the x-axis:

Let us use the Matlab function humps to generate a function with strong maxima points

Let us use the Matlab built in trapezoidal method first

Let us then use the quad function

Create a hello20.m

file/ save it/run it/ understand it (using trapz and cumtrapz) clear all;clc;clf

% this program demonstrates numerical integration x=linspace(-1,2,100); % create 100 pointes linearly spaced vector between -1 and 2 y=humps(x); area1=trapz(x,y); % this is the area under the curve. disp(' the calculated area under the curve is: - Hit any key to continue') area1 pause

% Now let us calculate the definite integraal again, but now let us show

% the cumulative aea under the curve ... The value of last accumulation

% must match the answer obtained for area1 !!! area2=cumtrapz(x,y); %Cumulative trapezoidal numerical integration.

33 plotyy(x,y,x,area2) grid on title(' humps and integral of humps') disp(' the final value is: Hit any key to continue -- ') area2(100) disp('notice - identical') pause

Note: on the graph, click the curser handle to read the data at any given point.

Check this box when this exercise is completed

Sometimes, depending on the function we are dealing with, it is not easy to determine an optimum segment widths.

The function quad numerically evaluates integral using adaptive Simpson quadrature.

The function quadl numerically evaluate integral using adaptive Lobatto quadrature.

Edit the hello21.m

file and add the following lines to the end of the above program then

(save/run): format long disp(' using quad function - hit any key to continue') area3=quad(@humps,-1,2); % numerically integrates the function humps between -1 and

2 area3 pause disp(' using quadl function - hit any key to continue') area4=quadl(@humps,-1,2); area4 pause format short

Now, let us do double integration:

Create hello22.m

(save it, run it, understand it, modify it to test for understanding) clc clear all clf

% double numerical integration ...

% let us create a gid data of x and y x=linspace(0,pi,20); y=linspace(-pi,pi,20);

34

[xx,yy]=meshgrid(x,y); % if you forgot meshgrid, list the data for [xx,yy] to see or type help meshgrid zz=sin(xx).*cos(yy)+1;

%let us see what we got disp('plot the resulting 3-d ') mesh(xx,yy,zz) xlabel('x-data');ylabel('y-data');zlabel('z-data') area=dblquad(@(xx,yy)sin(xx).*cos(yy)+1,0,pi,-pi,pi)

% note, we could have created a function (say we named it: myfunction) and

% made a function call to it to calculate zz

% this way, in the command line we would have written:

%area=dblquad('myfunction'.*cos(yy)+1,0,pi,-pi,pi)

Check this box when this exercise is completed

Differentiation:

Numerical differentiation gives the slope of the function at given points. Consequently, differentiation is sensitive to microscopic changes in a function and thus large slope results occur. Thus it is not recommended to do numerical differentiation. If we must say do differentiation on experimental data which typically contains inherent abrupt changes, we best first do least square curve fitting or other type then differentiate.

Let us do the following:

create our own experimental x ,y data

do a second order polynomial curve fit

determine the polynomial coefficients (equation)

evaluate a new y using the polynomial curve fit equation

plot original and smooth function

calculate the derivative of the polynomial and plot result

explore running slope calculations and compare.

This example is powerful – Understanding this example will make allow the “Proportianl

Derivative Controllers” in the Controls course to make a lot of sense.

Create hello23.m

save/run/ understand clc clear all clf x=0:.1:1; y=[-0.447 1.978 3.28 6.16 7.08 7.34 6 11 9.48 9.30 11.2]; n=2;% POLYNOMAIL ORDER =2 disp(' the equation of the 2nd order polynomial fit is: hit any key to continue') p=polyfit(x,y,n) pause

35

% now let us create more points between 0 and 1 xi=linspace(0,1,100); yi=polyval(p,xi); % calculate values of y new using the polynomial curve fit plot(x,y,'-o',xi,yi,'--') xlabel('x'),ylabel('y=f(x)') title('original data and 2nd order curve fit')

% the derivative of the polynomial is: pd=polyder(p);

% let us evalute the polynomial derivative and plot it

%Also, let us do a running slope of the oroginal function dyp=polyval(pd,x); %Evaluate the polydervative at values of x dy=diff(y)./diff(x); % compute the difference and use array division

%notice dy will have one element less than x

%let us shrink the x array by one element xd=x(1:end-1); % truncated away the last element disp('');disp(''); disp('now, let us plot the derivative of the polynomial fit') disp(' and the running slope of original equation') disp('hit any key to continue') plot(xd,dy,x,dyp,'-o') pause disp(' let us plot the original functions and their derivatives at the same time') subplot(211) plot(x,y,'-o',xi,yi,'--') xlabel('x'),ylabel('y=f(x)') title('original data and 2nd order curve fit') grid subplot(212) plot(xd,dy,x,dyp,'-o') title('derivative of the polynomial "o" and running slope') grid

Check this box when this exercise is completed

A little more fun with derivatives:

In 2-D data, the function gradient uses central differences to compute the slope in each direction at each data point. Forward differences are used at the initial points and backward differences are used at the final points so that the output has the same number of data points as the input. The function gradient is used primarily for graphical data visualization:

36 dz

In the following example, gradient computes dx and dz dy

from the tabulated data output of peaks. This data is then supplied to the function quiver which draws arrows normal to the surface at the supplied data points. The lengths of the arrows are proportional to the slopes at those data points.

Create hello24.m

run/save clc clear all clf

[x,y,z]=peaks(20); % produces 20 by 20 matrix of peaks dx=x(1,2)-x(1,1); % spacing in the x-direction dy=y(2,1) -y(1,1); % spacing in the y-direction

[dzdx,dzdy]=gradient(z,dx,dy); contour(x,y,z); %contour plot of z hold on %holds current plot and all axes properties quiver(x,y,dzdx,dzdy)%plots velocity vectors as arrows with components

%(u,v)at the points (x,y).

hold off title('Gradient arrow plot')

What if we wanted to know the curvature of the surface (change in slope at each point.)

This is calculated using del2 command.

Create hello25.m

save/run clc clear all clf

[x,y,z]=peaks(20); % produces 20 by 20 matrix of peaks dx=x(1,2)-x(1,1); % spacing in the x-direction dy=y(2,1) -y(1,1); % spacing in the y-direction disp('hit any key to continue')

[dzdx,dzdy]=gradient(z,dx,dy); contour(x,y,z); %contour plot of z hold on %holds current plot and all axes properties quiver(x,y,dzdx,dzdy)%plots velocity vectors as arrows with components (u,v)

%at the points (x,y). hold off title('Gradient arrow plot') pause

% let us view the curvature surface

L=del2(z,dx,dy); surf(x,y,z,abs(L)) shading interp title('Discrete LaPlacian color')

Check this box when this exercise is completed

37

Differential Equations:

Discussing the many ODE (ordinary differential equations) prided with Matlab is way beyond the intent of this getting started handout.) Thus we will basically review just a few commands we will need to use later on. Recall, you can always go to the help provided with Matlab – there is excellent listing and explanation provided.

Matlab solves a whole range of differential equations: Ordinary differential equations

(ODEs), differential algebraic equations (DAEs), Initial value problems (IVP), boundary value problems (BVP), and partial differential equations (PDEs)

This handout is NOT about differential equations, however, we will list a few examples of numerical solutions to some of the types of problems listed above.

First – let us solve an IVP ODE type problem:

Let us use the ode45 (Runge Kutta method of 4 th

to 5 th

order solver.)

Suppose the first order differential equation we have at hand is: dy

10

 y (note: y could represent Voltage across a capacitor in a series RC DC dt circuit.) By inspection RC = 1, and E =10V. Let us assume y(0) = 4 Volts (IVP)

The first step is to code the differential equation, then solve it

Here is the function (save the following as myfun1.m

) – make sure the function is saved in the same working directory as the main program coming up. function ydot=myfun1(t,y)

% this function forms the dy/dt (the differential equation.) ydot=10-y;

Now that you have coded the differential equation, you are ready to solve the ODE.

Save the following as hello26.m

and run it … change the initial value and see what happens. clc;clf;clear all tspan=[0 10]; y0=[4];

[t,y]=ode45(@myfun1,tspan,y0); size(t) size(y)

38 now at the prompt, plot y vs. t

>>plot(t,y)

Notice – looks like the transient response of an RC circuit (This is a 1 st

order ODE with non zero initial condition (value) )

Please go to Matlab help>>mathematics>>differential equations – there is so much on the subject.

Check this box when this exercise is completed

MGraphics

Several tricks were explored already – play with the figure handle and graph editor – lots of fun there. Also go to Matlab help>>graphics --- very nicely done.

NData

saving workspace data (subset ) and retrieving it

Let us now save a .mat file to the working directory and load it from the working directory

.mat file is typically the data file

Do the following: in the Matlab Command window, type dir. This will list the files available in the working directory. You may not see any .mat files -- probably all are .m files. type dir *.mat there will probably be no .mat files yet. note: you can also change directories and do many of the DOS commands from the matlab window.

It will be essential in some cases to run some programs and save only certain variables. Following that, we probably want to clear the workspace before loading the desired variables.

Read through the steps of the following program and run it. make sure you understand it. Type it at the command prompt

>>clear all

>>t= 0:0.01:10;

>>y=sin(t)

>>x=4*y;

% the variables in the workspace are now t,x,and y

>>who % this will list the workspace variables

% suppose we want to save in the file mydata only the variables t and x

>>save mydata t x

% now, let us explore the data we have created

>>t

>>x

>>y

% now let us clear the workspace variables

>>clear all

% now let us confirm we did that

Who

% you will see no listing of any variables – workspace is cleared.

% chek the directory -- please remember this dir *.mat

%now let us load the file from the directory load mydata who t disp('press any key to continue') x disp('press any key to continue')

Check this box when this exercise is completed

Saving to Excel and importing from Excel.- DDE

Let us create a small spreadsheet in excel – put data in rows 2,3,4 and columns

1,2,3,4 (just fill the specified grid with any numbers) and save the file in you

Matlab working directory as: test.xls Do not close the spreadsheet.

First we initiate the conversation with the spreadsheet as follows:

>>channel = ddeinit('excel','test.xls'); now, we request the data from the spreadsheet:

>>prices = ddereq(channel,'r2c2:r2c3'); % only two elements in row 2 are requested.

>>prices

Notice , it works --------------------

Now, let us write to an Excel spreadsheet. [ Note: A nicer command will be intoduced to the class as a later time]

39

40

First, let us create a matrix:

>> A=[1 2 3 4 5;-1 -2 -3 -4 -5;7 8 9 10 11]

Notice A is 3 X 5

>> rc = ddepoke(channel, 'r8c5:r10c9', A); % here we put the matrix in the same spreadsheet as above – but at different rows and columns.

Look at the spreadsheet …. Is the matrix added to the spreadsheet correctly?

Now that we are done communicating with the spreadsheet, we need to terminate the conversation:

>> ddeterm(channel);

- Reading data from Excel - Go to Matlab’s help>>search>>reading data from

Excel

Run the example provided --- it is very educational.

Check this box when this exercise is completed

41

OImages and Sounds

(To be continued ….)

P- Symbolic

(to come later)

Type Demo at the command prompt and explore all the help in the “Help Navigator” window.

Download