Introduction To MATLAB Programming And Functions - CUNY

5 downloads 117 Views 223KB Size Report
ENGR 103 Lesson 2. Introduction to MATLAB Programming and Functions. The real utility of Matlab (or programming environments in general) is the ability to ...
ENGR 103 Lesson 2 Introduction to MATLAB Programming and Functions The real utility of Matlab (or programming environments in general) is the ability to create complex programs by building up smaller constructs into a coherent whole.

Batch commands (The Script M-file) Until now, everything has been done in the command window. This is very inconvenient if we made a mistake and need to redo all the commands from the point of the mistake on (We all make mistakes). Also, we would like to keep a record of the work in the computer. MATLAB's solution is the batch mfile The batch file is a file that stores all the commands you wish to run in the order you wish them to run ########################################################### batch1.m (name of program) command 1 command 2 command 3 : : last command ########################################################### To make this file, 1. Go to file menu and select new. A text window will appear 2. Type the desired commands 3. Go to file menu and select save 4. Give desired name (batch1) Once in MATLAB, the batch program is implemented by simply typing >> batch1 Note that batch1 is really batch1.m (the m extension indicates it is a MATLAB file). This is necessary for Matlab to interpret the file as a batch file. Example: Redo the last example using a batch file

Iterative MATLAB tools All programming languages have tools that allow operations to be performed repeatedly. Like all other languages, MATLAB has an unconditional 'for' construnct and a conditional 'while' construct. The (for) loop. The for loop allows a group of operations to be performed as many times as desired. The counting is done by a counter variable whose initial and final values determine the number of iterations that are performed. In addition, since this counter variable changes, we can make use of this counter for calculation purposes, addressing purposes, etc. Please do all following exercises as batch programs. When possible, simply copy and paste the programs into a batch file to save time. Problem: Implement the following code and comment on the results. for i=1:10 x(i)=i y(i)=x(i)^2; end Question? What are the sizes of x and y? Problem: Implement the same procedure using array operations. In this case, the sample increment is 1 which may be to coarse. If we want a finer sampling (.01 for example), we may try for i=1:.01:10 x(i)=i; y(i)=x(i)^2; end Question? Why does this not work?

Answer The previous procedure fails because you are trying to place elements in a vector with non-integer addresses. Matlab only allows addresses to be positive integers. To circumvent this procedure, try the following p=1 for i=1:.01:10 x(p)=i; y(p)=x(p)^2; p=p+1; end plot(x,y) Question? Why does this procedure work? The previous example used loops to generate function tables that could just as easily be generated using array operations. Array operations are useful whenever the relationship is explicit i.e. y=f(x). However, many times, the output is not clearly a function of an input. Loops are necessary when there is no simple algebraic relationship between input and output. One example of importance are so called map functions which take the form x n +1 = f ( x n ) . You should convince yourself that the map is uniquely determined if x1 is given. N=1 N=2 N=3 N=4 Example

X1=X1 X 2 = f ( X1) X 3 = f ( f ( X1 ))

X 4 = f ( f ( f ( X 1 ) ))

ax n + b for specific coefficient values cxn + d a=1, b=2, c=1, d=1. And initial value x(1)=3. This example ax + b has f ( x ) = ; the program to implement this sequence is cx + d a=1; b=2; c=1; d=1;

Consider the map x n +1 =

x(1)=x(1); n(1)=1;

initial conditions

for i=1:20 x(i+1)=(a*x(i)+b)/(c*x(i)+d); %recursion n(i+1)=i+1; % only needed because of the plot end plot(n,x) Questions? What is the n for? What happens if you change x(1)? What happens if you change the coefficients? Explore 2 . This is the same 3 − ( x − 1) 2 2 as solving x − 2 = 0 . This can be written as x = . If 2 3 − ( x n − 1) 2 we are trying to solve for x, we can write x n +1 = 2 and if a limit exists, it will equal 2 . If the program is implemented correctly, the following iterative approximation is obtained.

Example: Suppose I want to calculate

iterative solution for sqrt 2 x1=1 guess 1.5 1.45 1.4 1.35 1.3 xn

1.25 1.2 1.15 1.1 1.05 1

0

5

10

15

20

25

n

Be careful. This method, which called the Direct Iterative Method, does not always converge to an answer. Later we will learn when this method converges and when it doesn’t.

Another application of loops is in summing a sequence {a1 , a2 , a3 ,L an } where the nth term is expressible as a function of n. Examples n =10

1)

∑n

a(n)=n



a(n)= n 2

n =1 n =10

2)

n2

n =1 n=∞

1 3) ∑   2 n =1  

n

1 a ( n) =   2

n

Question? Can we really sum an infinite series? The following procedure allows you to sum the series keeping track of all partial sums. S(1)=a(1) for k=2:n S(k)=S(k-1)+a(k); end Question?

Why is S(1)=a(1)?

The sum and the partial sum problem can also be implemented using the Matlab sum and cumsum function where the terms are stored in an array. Example an=[1:10] % sequence of positive integers from 1 to 10 Sn=cumsum(an) 1 3 6 10 15 21 28 36 45 55 S=sum(an) 55 The following program allows you to take the product of a sequence of numbers P(1)=a(1) for k=2:n P(k)=P(k-1)*a(k); end

Problem: Calculate the partial product (1/2)*(2/3)*(3/4)*...*(n/n+1) for n=50 Question? What should you get? Hint: look to cancel terms in the product. Matlab’s prod and cumprod function performs the same task if the sequence is stored in an array. Example The above problem “Calculate the partial product (1/2)*(2/3)*(3/4)*...* n/(n+1) for n=50” can be solved as follows n=[1:50]; an=(n)./(n+1); Pn=cumprod(an); P=prod(an); The (while) loop. This construct is used when you want to iterate a procedure until some condition is satisfied. This is often the case when you are calculating a sequence that should converges to a limit. Example: While loop is used to stop an iteration when a desired accuracy has been reached. We know from calculus that e x =



∞ 1 xk e = . If x=1, ∑ k! ∑ k! ≈ 2.7183 k =0 k =0

Note that since the sum starts from zero, we need to change the sum variable to k ′ = k + 1 ⇒ k = k ′ − 1 which results in

e=



1

∑ (k − 1)! ≈ 2.7183

k ′ =1

The problem is to calculate the partial sum approximations of the infinite sum as a function of n until are within 0.001 of the limit.

err=1;

%Choose initial error to be high so that the %while loop will enter the first time

S(1)=1; n(1)=1; x=1; k=2; while (err > .001) n(k)=k; S(k)=S(k-1)+(x^(k-1))./factorial(k-1); %prod(1:km) = km ! Another way of simulating a factorial. err=abs((exp(x)-S(k))/exp(x)); k=k+1; end plot(n,S,'o') Question? How many terms did you need? If you do the same for x=2, do you need more or less terms?

Conditional Tools (The if statement) Conditional tools allow programs to decide between different courses of action based on the status of a control condition. This allows many different outcomes and processes to be coded in a simple way. Conditional operations require both relational as well as logical operators to test the control condition Relational operators eq - Equal == ne - Not equal ~= lt - Less than < gt - Greater than > le - Less than or equal = Logical operators and - Logical AND & or - Logical OR | not - Logical NOT ~ xor - Logical EXCLUSIVE OR any - True if any element of vector is nonzero all - True if all elements of vector are nonzero The if tests if the condition is true or false. If the condition is true, the commands are executed, otherwise the program skips to the next segment.

If (Logical Expression 1 is true) {Commands} Elseif (Logical Expression 2 is true) {Commands} else {Commands} end Examples of Logical expressions utilizing conditional and relational operators are: Examples If (x > 1 & x < 5) If (x > 20 | x < 5) If (x == 3) If (x ~= 1) Example: (Note how the conditional branches are isolated so that you can see the different branches better) Design a vector of length 100 whose elements are • 2 times the address element if the address is between 10 and 20, • whose elements = 5 if the address is less than 10, • whose elemnts are equal to the address if the address is above 20 but less than 50 • and whose elements are one for any other case. N=100; x=zeros(N,1);%Initialization. This provides space to store %the results. for k=1:N n(k)=k; if (k < 10) x(k)=5; elseif (k >= 10 & k 20 &k < 50) x(k)=k; else x(k)=1; end end plot(n,x,'o')

Application of “rem” to build discontinuous signals. (The remainder “rem” function) The remainder function rem performs modolu arithmitic. Suppose we take 6 and divide by 4. This gives 6=1*4+2 Here 2 is the remainder, 1 is the divisor and 4 is the modulus. We say 6=2 (modulus 4) and the MATLAB syntax is rem(6,4)=2 Example The rem function can test if a number is even or odd. rem(37,2) 1 % therefore 37 is odd rem(1990,2) 0 % therefore 1990 is even Question? What does rem(n,1) do? What does rem(n,0) do? Example Create a 10 X 10 matrix whose elements are 1 if the sum of row address + column address is even and whose elements are 0 otherwise N=10 for i=1:N for j=1:N if (rem((i+j),2)==0) M(i,j)=1; else M(i,j)=0; end end end Question? What did we generate?

The function M-file (Building your own custom functions) A function is a set of operations that process a set of inputs and produce a set of outputs. Custom functions can be built in MATLAB with the following syntax. The inputs and outputs could be scalars, vectors or matrices. Below, we have the syntax (the first line in the function m-file) of a function accepting m inputs and returning n outputs. function [out1,out2,

,outn]=fname(in1,in2, ...,inm)

Example: Make a function cosn(x)=cos(x)^n filename is cosn.m MATLAB knows it is a function file rather than a batch file because the first word is function. ######################################################## function y=cosn(x,n) y=cos(x).^n; ######################################################## The function call in MATLAB is of the form x=[0:2*pi/100:2*pi]; n=3; y=cosn(x,n); plot(x,y) Note that the function accepted a vector input x. Problem Using cosn, plot cos(x)^n on the interval 0:2*pi for n=1:10 on the same graph. What do you notice? In many cases, a function has multiple definitions on different domains. These functions can be implemented using conditional statements. Example: Create the following function and plot the results on the interval − 2 ≤ x ≤ 2

y = x2 0 ≤ x ≤ 1 y = exp( x) x > 1 y=0 x=0 & x 1) y=exp(x); else y=0; end ######################################################## Once the function is in place, we can sample it on an appropriate domain and graph the result.

xv=[-2:.01:2]; for j=1:length(xv) x=xv(j); yv(j)=funtest(x); end plot(xv,yv) 8

7 6

5

4 3

2 1

0 -2

-1.5

-1

-0.5

0

0.5

1

1.5

2

Example: Let us generate a periodic signal used in engineering all the time, an alternating square wave of height 5 of period 2 for 5 periods. Mathematically, if if if if

0 1 2 3