matlab-tutorial 1 class eces-304 presented by : shubham bhat

33
MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Upload: clifford-austin

Post on 06-Jan-2018

221 views

Category:

Documents


1 download

DESCRIPTION

Commercial “Matrix Laboratory” package which operates as an interactive programming environment. The Programming language is exceptionally straightforward since almost every data object is assumed to be an array. Graphical output is available to supplement numerical results. Online help is available from the MATLAB prompt (a double arrow), both generally (listing all available commands): >> help (a long list of help topics follows) and for specific commands: e.g.>> help fft (a help message on the fft function follows) MATLAB- Matrix Algebra

TRANSCRIPT

Page 1: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

MATLAB-Tutorial 1 Class ECES-304

Presented by : Shubham Bhat

Page 2: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

MATLAB- Introduction (with examples)

•Vectors•Building Matrices•Relations and Logical Operators•Colon Notation•Functions•Plotting

MATLAB Programming (with examples)

•Variable Assignment •Branching•For Loops•While Loops•Recursion

Overview

Page 3: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Commercial “Matrix Laboratory” package which operates as an interactive programming environment.

The Programming language is exceptionally straightforward since almost every data object is assumed to be an array.

Graphical output is available to supplement numerical results. Online help is available from the MATLAB prompt (a double arrow), both generally (listing all available commands):

>> help (a long list of help topics follows)

and for specific commands: e.g.>> help fft (a help message on the fft function follows)

MATLAB- Matrix Algebra

Page 4: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

MATLAB- Window

Page 5: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Vectors

Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between brackets, and set it equal to a variable.

a = [1 2 3 4 5 6 9 8 7]

Matlab should return: a = 1 2 3 4 5 6 9 8 7

Let's say you want to create a vector with elements between 0 and 20 evenly spaced in increments of 2 (this method is frequently used to create a time vector):

t = 0:2:20 t = 0 2 4 6 8 10 12 14 16 18 20

t= 0:0.1:1

Page 6: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Manipulating vectors is almost as easy as creating them. First, suppose you would like to add 2 to each of the elements in vector 'a'. The equation for that looks like:

b = a + 2 b = 3 4 5 6 7 8 11 10 9

Now suppose, you would like to add two vectors together. If the two vectors are the same length, it is easy. Simply add the two as shown below:

c = a + b c = 4 6 8 10 12 14 20 18 16

Subtraction of vectors of the same length works exactly the same way.

d = a - b

Manipulating Vectors

Page 7: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Entering matrices into MATLAB is the same as entering a vector, except each row of elements is separated by a semicolon (;).

B = [1 2 3 4;5 6 7 8;9 10 11 12]

Matrices in MATLAB can be manipulated in many ways. For one, you can find the transpose of a matrix using the apostrophe key:

C = B'

It should be noted that if C had been complex, the apostrophe would have actually given the complex conjugate transpose. To get the transpose, use .' (the two commands are the same if the matrix is not complex).

Now you can multiply the two matrices B and C together. Remember that order matters when multiplying matrices.

D = B * C

Matrices

Page 8: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Another option for matrix manipulation is that you can multiply the corresponding elements of two matrices using the .* operator (the matrices must be the same size to do this).

E = [1 2;3 4]F = [2 3;4 5]G = E .* F

E = 1 2 3 4 F = 2 3 4 5 G = 2 6 12 20

If you have a square matrix, like E, you can also multiply it by itself as many times as you like by raising it to a given power.

E^3 ans = 37 54 81 118

If wanted to cube each element in the matrix, just use the element-by-element cubing.

E.^3 ans = 1 8 27 64

Manipulating Matrices

Page 9: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

You can also find the inverse of a matrix:

X = inv(E) X = -2.0000 1.0000 1.5000 -0.5000

or its eigenvalues:

eig(E) ans = -0.3723 5.3723

There is even a function to find the coefficients of the characteristic polynomial of a matrix. The "poly" function creates a vector that includes the coefficients of the characteristic polynomial.

p = poly(E) p = 1.0000 -5.0000 -2.0000

Remember that the eigenvalues of a matrix are the same as the roots of its characteristic polynomial:

roots(p) ans = 5.3723 -0.3723

Manipulating Matrices

Page 10: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Here, you should think of 1 as "true" and 0 as "false."

The notations &, |, ~ stand for "and,""or," and "not," respectively.

The notation == is a check for equality.

a=[1 0 1 0]b=[1 1 0 0]a==ba<=b~aa&ba & ~aa | ba | ~a

There is a function to make all entries to a matrix as zero or ones.

c=zeros(1,4)d=ones(1,4)

Relations and Logical Operations

Page 11: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Matlab offers some powerful methods for creating arrays and for taking them apart. x=-2:1length(x)a=magic(5)a(2,3)

Now we will use the colon notation to select a column of a. a(2,:)a(:,3)aa(2:4,:)a(:,3:5)a(2:4,3:5)a(1:2:5,:)

You can put a vector into a row or column position within a. a(:,[1 2 5])a([2 5],[2 4 5])

Colon Notation

Page 12: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

You can also make assignment statements using a vector or a matrix.

b=rand(5)

b([1 2],:)=a([1 2],:)

a(:,[1 2])=b(:,[3 5])

a(:,[1 5])=a(:,[5 1])

a=a(:,5:-1:1)

This has been a sample of the basic MATLAB functions and the matrix manipulation techniques.

By typing help commandnameyou will get access to descriptions of all the Matlab functions.

Colon Notation

Page 13: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

To make life easier, Matlab includes many standard functions. Each function is a block of code that accomplishes a specific task. Matlab contains all of the standard functions such as sin, cos, log, exp, sqrt, as well as many others.Commonly used constants such as pi, and i or j for the square root of -1, are also incorporated into Matlab.

sin(pi/4)ans = 0.7071

To determine the usage of any function, type help [function name] at the Matlab command window.

Matlab even allows you to write your own functions with the function command;

a = magic(4)

Take the transpose of a: a'

Functions

Page 14: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Note that if the matrix A has complex numbers as entries then the MATLAB function taking A to A' will compute the transpose of the conjugate of A rather than the transpose of A.

Other arithmetic operations are easy to perform. 3*a

-a

a+(-a)

b = max(a)max(b)

Some MATLAB functions can return more than one value. In the case of max the interpreter returns the maximum value and also the column index where the maximum value occurs.

[m, i] = max(b)

min(a)

Functions - Continued

Page 15: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

We can use matrix multiplication to check the "magic" property of magic squares.

a = magic(5)b = ones(5,1)a*bv = ones(1,5)v*a

Matlab has a convention in which a dot in front of an operation usually changes the operation. In the case of multiplication, a.*b will perform entry-by-entry multiplication instead of the usual matrix multiplication.

a.*b x=5,x^2a*aa^2a.^2 adiag(a)

Functions - Continued

Page 16: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

diag(diag(a))

There are many functions which we apply to scalars which Matlab can apply to both scalars and matrices.

sin(d)exp(d)log(d)abs(d)

You can write your own functions. ( use MEditor to write functions or programs)

The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments. In this case, there are up to two input arguments and one output argument.e.g. falling.m

function h = falling(t)g=9.8;h = 1/2*g*t.^2;

Functions - Continued

Page 17: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

It is also easy to create plots in Matlab. Suppose you wanted to plot a sine wave as a function of time. First make a time vector (the semicolon after each statement tells Matlab we don't want to see all the values) and then compute the sin value at each time.

t=0:0.25:7;y = sin(t);plot(t,y)

The plot contains approximately one period of a sine wave. Basic plotting is very easy in Matlab, and the plot command has extensive add-on capabilities.

Plotting

Page 18: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

MATLAB is also a programming language.

By creating a file with the extension .m you can easily write and run programs.

If you were to create a program file myfile.m in the MATLAB language, then you can make the command myfile from MATLAB and it will run like any other MATLAB function.

You do not need to compile the program since MATLAB is an interpretative (not compiled) language.

Such a file is called an m-file.

1. Assignment

Assignment is the method of giving a value to a variable.

We write x=a to give the value of a to the value of x.

Programming in MATLAB

Page 19: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Here is a short program illustrating the use of assignment.

function r=modular(a,d)% r=modular(a,d). If a and d are integers, then% r is the integer remainder of a after % division by d. If a and b are integer matrices,% then r is the matrix of remainders after division% by corresponding entries. Compare with REM.

r=a-d.*floor(a./d);

You should make a file named modular.m and enter this program exactly as it is written.

Now assign some integer values for a and d. Run modular(a,d)

This should run just like any built-in MATLAB function.

Assignment Example

Page 20: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Type help mod

This should produce the five lines of comments which follow the % signs.The % signs generally indicate that what follows on that line is a comment which will be ignored when the program is being executed.

MATLAB will print to the screen the comments which follow the "function" declaration at the top of the file when the help command is used. In this way you can contribute to the help facility provided by MATLAB to quickly determine the behavior of the function.

Type type mod

This will list out the entire file for your perusal. What does this line program mean? The first line is the "function declaration." In it the name of the function (which is always the same as the name of the file without the extension .m), the input variables (in this case a and d), and the output variables (in this case r) are declared. Next come the "help comments" which we have already discussed.

Assignments- Continued

Page 21: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Finally, we come to the meat of the program.

The variable r is being assigned the value of a-d.*floor(a./d);

The operations on the right hand side of the assignment have the meaning which you have just been practicing (the / is division) with the "." meaning the entry-wise operation as opposed to a matrix operation.

Finally, the ";" prevents printing the answer to the screen before the end of execution.

You might try replacing the ";" with a "," and running the program again just to see the difference.

Assignments- Continued

Page 22: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Branching is the construction

if <condition>, <program> end

The condition is a MATLAB function usually, but not necessarily with values 0 or 1 (later I will discuss when we can vary from this requirement), and the entire construction allows the execution of the program just in case the value of condition is not 0.

If that value is 0, the control moves on to the next program construction.

You should keep in mind that MATLAB regards a==b and a<=b as functions with values 0 or 1.

Frequently, this construction is elaborated with if <condition1>, <program1> else <program2> end

In this case if condition is 0, then program2 is executed.

Branching

Page 23: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Another variation is

if <condition1>, <program1> elseif <condition2>, <program2>end

Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is not 0, then program2 is executed, and otherwise control is passed on to the next construction.

Here is a short program to illustrate branching.

function b=even_number(n)% b=even(n). If n is an even integer, then b=1% otherwise, b=0.if mod(n,2)==0,

b=1; else b=0;

end

Branching Example

Page 24: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

A for loop is a construction of the form for i=1:n, <program>, end Here we will repeat program once for each index value i. Here are some sample programs. The first is matrix addition.

function c=addition(a,b)% c=add(a,b). This is the function which adds % the matrices a and b. It duplicates the MATLAB % function a+b.[m,n]=size(a);[k,l]=size(b);if m~=k | n~=l,

r='ERROR using add: matrices are not the same size'; return,

endc=zeros(m,n);for i=1:m,

for j=1:n, c(i,j)=a(i,j)+b(i,j);

endend

For Loops

Page 25: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

The next program is matrix multiplication.

function c=mult(a,b)% c=mult(a,b). This is the matrix product of % the matrices a and b. It duplicates the MATLAB % function c=a*b.

[m,n]=size(a);[k,l]=size(b);if n~=k, c='ERROR using mult: matrices are not compatible for multiplication',return,end,c=zeros(m,l);for i=1:m, for j=1:l, for p=1:n, c(i,j)=c(i,j)+a(i,p)*b(p,j); end endend

For Loops- Example

Page 26: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

For both of these programs you should notice the branch construction which follows the size statements. This is included as an error message.

In the case of add, an error is made if we attempt to add matrices of different sizes, and in the case of mult it is an error to multiply if the matrix on the left does not have the same number of columns as the number of rows of the the matrix on the right.

Had these messages not been included and the error was made, MATLAB would have delivered another error message saying that the index exceeds the matrix dimensions.

You will notice in the error message the use of single quotes.

The words surrounded by the quotes will be treated as text and sent to the screen as the value of the variable c.

Following the message is the command return, which is the directive to send the control back to the function which called add or return to the prompt.

Error Message

Page 27: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

In the construction for i=1:n, <program>, end

the index i may (in fact usually does) occur in some essential way inside the program.

MATLAB will allow you to put any vector in place of the vector 1:n in this construction.

Thus the construction for i=[2,4,5,6,10], <program>, end is perfectly legitimate.

In this case program will execute 5 times and the values for the variable i during execution are successively, 2,4,5,6,10.

For Loops- more examples

Page 28: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

A while loop is a construction of the form

while <condition>, <program>, end

where condition is a MATLAB function, as with the branching construction. The program program will execute successively as long as the value of condition is not 0. While loops carry an implicit danger in that there is no guarantee in general that you will exit a while loop. Here is a sample program using a while loop.

function l=twolog(n)% l=twolog(n).l is the floor of the base 2% logarithm of n.l=0;m=2;while m<=n l=l+1; m=2*m;end

While Loops

Page 29: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Recursion is a devious construction which allows a function to call itself. Here is a simple example of recursion

function y=twoexp(n)% y=twoexp(n). This is a recursive program for computing% y=2^n. The program halts only if n is a nonnegative integer.

if n==0, y=1;

else y=2*twoexp(n-1);end

The program has a branching construction built in. Many recursive programs do.

The condition n==0 is the base of the recursion. This is the only way to get the program to stop calling itself. The "else" part is the recursion. Notice how the twoexp(n-1) occurs right there in the program which is defining twoexp(n)!

The secret is that it is calling a lower value, n-1, and it will continue to do so until it gets down to n=0.

Recursion

Page 30: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

A successful recursion is calling a lower value.

There are several dangers using recursion.

The first is that, like while loops, it is possible for the function to call itself forever and never return an answer.

The second is that recursion can lead to redundant calculations which, though they may terminate, can be time consuming.

The third danger is that while a recursive program is running it needs extra space to accommodate the overhead of the recursion.

In numerical calculations on very large systems of equations memory space is frequently at a premium, and it should not be wasted on program overhead. With all of these bad possibilities why use recursion?

It is not always bad; only in the hands of an inexperienced user. Recursive programs can be easier to write and read than nonrecursive programs.

Usage of Recursion

Page 31: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

'(ch2p1)' % Display label.'How are you?' % Display string.-3.96 % Display scalar number -3.96.-4+7i % Display complex number -4+7i.-5-6j % Display complex number -5-6j.(-4+7i)+(-5-6i) % Add two complex numbers and % display sum. (-4+7j)*(-5-6j) % Multiply two complex numbers and % display product.M=5 % Assign 5 to M and display.N=6 % Assign 6 to N and display.P=M+N % Assign M+N to P and display.

Main Program- 1

% Nise, N.S. % Control Systems Engineering, 4th ed. % John Wiley & Sons, Hoboken, NJ, 07030%% Control Systems Engineering Toolbox Version 4.0 % Copyright © 2004 by John Wiley & Sons, Inc.% % Chapter 2: Modeling in the Frequency Domain

Page 32: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

Main Program-2

Below we show an example of a sample program which consists of all the functions we studied so far.

close all;clear all;clc;

%%%%%%%%%%%%%%%%%%%%%%%%%% variable assignments%%%%%%%%%%%%%a = 4;b = 3;c = [1 3; 4 5];d = [2 3; 3 4];

%%%%%%%%%%%%%%%%%%%%%%%%% function calls%%%%%%%%%%%%%%%%

t = modular(a,b);r = even_number(a);m = addition(c,d);s =mult(c,d);

Page 33: MATLAB-Tutorial 1 Class ECES-304 Presented by : Shubham Bhat

To quit Matlab:

At the MATLAB prompt type quit or by type exit

Quitting Matlab