Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language...

29
Matlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting Matlab Double click on the MATLAB icon ---- This starts the Matlab Desktop The Desktop manages the Command Window Depending upon how the default is set up, you might see 2 additional windows, namely Command History and Launch Pad Windows to the left. Command Window is used to communicate with the Matlab program. Matlab displays the prompt “ >> “ or ‘EDU>>’ for student Edition. It indicates that Matlab is ready to receive instructions. Matlab as a Calculator >> 4+6= ans= 10 >>4*25+6*20+8*10= ans= 300

Transcript of Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language...

Page 1: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Matlab Primer

Matlab is a programming language and also provides software environment for using the language effectively.

Starting Matlab

Double click on the MATLAB icon ---- This starts the Matlab Desktop

The Desktop manages the Command Window Depending upon how the default is set up, you might see 2 additional windows, namely Command History and Launch Pad Windows to the left.

Command Window is used to communicate with the Matlab program.Matlab displays the prompt “ >> “ or ‘EDU>>’ for student Edition.It indicates that Matlab is ready to receive instructions.

Matlab as a Calculator

>> 4+6=ans= 10>>4*25+6*20+8*10=ans= 300

Basic Operations:

A+B AdditionA-B SubtractionA*B MultiplicationA/B Right divisionA\B Left divisionA^B ExponentiationThese operations follow set of rules called Precedence All mathematical statements are evaluated starting from left to right. Exponentiation is performed first having the highest precedence. This followed by multiplication and division with equal precedence, followed by addition and subtraction with equal precedence.

Page 2: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Where Parentheses appear, evaluation begins with innermost pair and proceeds outwards.

Examples:Make note how precedence and parentheses change answers.

>>7+4*6ans= 31>>7+(4*6)ans= 31>>(7+4)*6ans= 66>> 5^2-10+8/4*2ans= 16>> 5^2-10+8/(4*2)ans= 16>>4*3^2-7ans= 29>>4*(3^2)-7ans= 29>>(4*3)^2-7ans= 137Remark Use parentheses to avoid any confusion with precedence.

Function and Variables

Functions and Variable names must begin with a letter and must contain less than 32 characters. The rest of the name can contain digits, letters and underscoreCharacters.

Page 3: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Matlab is case sensitive. For example a name of a variable A12w is different from a12w or a12W or A12W. So one of them is defined and by mistake you try to use the other, Matlab will give you an error message.

Example4 erasers, 6 pads, and 2 discsCost 25; 52; and 99 cents>>erasers=4erasers= 4>>pads=6pads= 6>>discs=2discs= 2>>items=erasers+pads+discsitems= 12>>cost=erasers*25+pads*52+discs*99cost= 610

Remarks(a) Escape, horizontal and vertical arrow, Backspace, delete, end commands perform the commonly assigned tasks(b) Semicolon at the end of each statement will suppress printing to screen (c) Several statements can be put on a line provided semicolons separate them.In the above example, one can write the program as follows:>>erasers=4; pads=6; discs=2;>>items=erasers+pads+discs; cost=erasers*25+pads*52+discs*99cost= 610Instead of semicolons, one can use commas to separate statements. However, commas will not suppress writing to the screenPredefined constants and functionsThere are several predefined special constants and functions in Matlabans temporary variable containing the most recent answer.eps specifies the accuracy of floating point precision

Page 4: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Inf infinitypi the number i,j the imaginary unit NaN undefined numerical value Some Special FunctionsSome of the commonly used functions are listed below. For additional list consult Help

max(x) largest component of array xmin(x) smallest component of array x sin(x) trigonometric sinecos(x) trigonometric cosinesec(x) trigonometric secantcsc(x) trigonometric cosecanttan(x) trigonometric tangentcot(x) trigonometric cotangentexp(x) Exponentiallog(x) Natural logrithmlog10(x) log to the base 10log2(x) log to the base 2sqrt(x) square rootasin(x) inverse sineacos(x) inverse cosineatan(x) inverse tangentasec(x) inverse secantacsc(x) inverse cosecantatan2(x) four quadrant inverse tangent aength(x) computes the number of elements in array xmean(x) computes the mean of x std(x) computes the standard deviation of xcosh(x) hyperbolic cosine =(exp(x)+exp(-x))/2sinh(x) hyperbolic sine =(exp(x)+exp(-x))/2tanh(x) hyperbolic tangent=sinh(x)/cosh(x)coth(x) hyperbolic cotangent=cosh(x)/sinh(x)sech(x) hyperbolic secant=1/cosh(x)csch(x) hyperbolic cosecant=1/sinh(x)acosh(x) inverse hyperbolic cosineasinh(x) inverse hyperbolic sineatanh(x) inverse hyperbolic tangentacoth(x) inverse hyperbolic cotangent

Page 5: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

acsch(x) inverse hyperbolic cosecantasech(x) inverse hyperbolic secantabs(x) absolute value of xdet(A) evaluates the determinant of matrix Ainv(A) evaluates the inverse of matrix Acond(A) evaluates the condition number of matrix Aeig(A) evaluates the eigen-values of matrix A

Remarks While programming in Matlab try not to use special constants as variable namesIf you do not remember the name of a variable in a Matlab code, just type who. The variable in the above example are cost, items, discs, pads, and erasers.

Problems1. Given x=5+4i and y=3-7i. Compute

U=x+y; v=x*y; w=x/y; p=xy^2; q=exp(y); r=(x)^.5 2.-(a ) The volume and surface area of a sphere are given by Vol=(4/3)r 3

and S=4r2 respectively, where r is the radius of the sphere. Use Matlab to determine the radius of a sphere with 30% more volume than that of radius 5 feet.

(b) For the larger sphere does the surface area also increase by 30%? ( c ) Determine the radius of the sphere whose surface area is 30% larger than the surface area of a sphere of radius 5. (d) Compare the results from (a) and (c).

M-files or Script filesProgramming in Matlab can be carried out in two different ways

(i) In the interactive mode where commands and statement etc are entered directly in the command window

(ii) By running a Matlab program stored in script files. This type of file contains Matlab commands etc. and have an extension “.m”. So running it is equivalent to typing all the command one at a time in the command window. You can run the file by typing its name at the command window prompt.

(iii) Use of “ …” at the end of a line will continue that statement to the next line. Good programming practice suggests that it is better break a large statement into several short statements.

Page 6: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

How to write a script or M-fileIn command window toolbar select New from File menu, then select M-file;This opens up a new edit window—without >> prompt;Type in the file or program—Can use Editor/Debugger to create or debug the file;Then use Save from the File menu – Editor will automatically provide the “.m” extension and save it on the hard disc.Example% program example.m%This program computes the cost of various itemserasers=4;pads=6;discs=2;items=erasers+pads+discs; cost=erasers*25+pads*52+discs*pp;average cost=cost/items

After this file is saved, it can be run any time in the command window by typing example after the prompt >>--Notice no “.m” extension is required while running the script file.

In-line Functions

Some times it is convenient to pass character string name of a function into a function (special function programmed by you) for evaluation.There are several ways one can achieve this using eval, feval and inline.Let us say you have created a script file called myfunc, then these functions will work as follows:>>a=eval(‘myfunc(x)’); or>>a=feval(‘myfunc’,x);In some cases the entire function is expressed as a character string in the program as:

Myfunc= “the math expression”,In such situation feval does not work. However, one can use the other two ways of evaluation as:>>a=eval(myfunc) or>>myinfun=inline(myfunc,’x’); % this converts myfunc to myinfun(x).>>a=feval(myinfun,x)---now feval works

Page 7: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Examples---Note command window has >> prompt(1)-------Function y=myfunc(x)% this is my functiony=x^3-2;

After saving this function file, in the command window>>x=2; >>a=feval(‘myfunc’,x)a= 6(2)function f=myfunc(x,y)% this is my functionf=10*(y-x)^2+(2-y)^2;In command window>>x=1; y=2;>>a=feval(myfunc,x,y) or>>a=eval(myfunc(x,y)a= 11(3)---Note the single quote in defining myfunc below>>myfunc=’10*(y-x)^2+(2-x)^2’;>>x=1;y=2;>>myinfun=inline(myfunc,’x’,’y’);>>a=eval(myfunc) or>>a=feval(myinfun,x,y)a= 11(4)function f=myfunc(x,y,t)f1=10*(y-x)^2+(2-x)^2;f2=5*x*tf=[f1,f2];Now feval etc will give two outputs

Page 8: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

RemarksWhen the function has to be computed many times in the execution of a program, feval is considered to be more efficient.

Problems1. Write a script file to evaluate the following function: Y=2+cos(x) for –1 ≤ x ≤ 5; Evaluate y for x=-.5, 3 and 4.5 and check your answer by hand.

Reading Input

Some times it is convenient to read in data rather than edit the code every time the data is changed. The following example shows this:Example% program example.m%This program computes the cost of various itemserasers=4;pads=6;discs=input(‘enter number of discs’);items=erasers+pads+discs; cost=erasers*25+pads*52+discs*pp;average cost=cost/itemsWhen this script is run in the command window, it will prompt you for the number of discs. Once the number is entered, the program will be executed and the result will be displayed.

Arrays

Matlab can handle the collection of numbers called arrays as if they were a single variable>>x=[0,.1*pi,.2*pi,……,pi];>>y=sin(x)y=

Alternate Representation

>>x=(0:.1:1)*pi; or>>x=linspace(0,pi,10);

Array Orientation

Page 9: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

>>c=[1;2;3;4;5]c= 1 2 3 4 5>> a=1:5a=1,2,3,4,5>>b=a’b=1 2 3 4 5>>c=b’c=1,2,3,4,5

RemarksCommas and spaces are used to separate elements in a rowSemicolons are used to separate rows

Array Operations

+ array addition- array subtraction+ scalar-array addition- scalar-array subtraction

.* array multiplication . / array right division .\ array left division . ^ array exponentiation : represents entire row or column of an arrayExample>> a=[4,2]; b=[3,6]; c=2;>>d=a+bd= [7,8]>>d=a-cd= [1,-4]

Page 10: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

>> d=a+cd= [6,4]>>d=a-cd= [2,0]>>d=a.*bd= [12,12]>>a./bd= [4/3,2/6]>>d=a.\bd= [4\3,2\6]>>d=a.^bd= [4^3,2^6]>>d=3.^ad= [3^4,3^2]>>d=a.^3d= [4^3,2^3]

Matrix Representation

>>g=[1 2 3 4;5 6 7 8]g=1 2 3 4 5 6 7 8>>g-2ans= each element will be subtracted by 2

>>a=[1,2,3;4,5,6;7,8,9]>>b=[.1 0 .2;0 .3 1;.2 .4.6]>>a+b=1.1 2.0 3.2 4.0 5.3 7.0

7.2 8.4 9.6>>a-b=0.9 2.0 2.8 4.0 4.7 5.0 6.8 7.6 8.4

Page 11: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Special Matrices

>>ones(3)ans=1 1 1 1 1 1 1 1 1>>zeros(2,5)ans= 0 0 0 0 0 0 0 0 0 0>>eye(3)ans= 1 0 0 0 1 0 0 0 1>>eye(2,4)ans= 1 0 0 0 0 1 0 0

Problems Let a=[7 14 –6;12 –5 9;-5 7 15]; b=[3 –2 1;6 8 –5;7 9 10]; 1. Compute c=a+b; d=a+b+eye(3); f=a*b; g=a*one(3); h=one(3)*a; p=a*eye(3); q=eye(3)*a;

Additional Vector and Matrix Computation

x = [1 2 3 ]y = [5 10 15]

Addition and subtraction of vectors or matrices of the same dimensions are defined in the usual way

x + y = [1+5 2+10 3+15] = [7 12 18]

Component-by-component(scalar) product of vectors x and y is indicated as

x .* y = [(1)(5) (2)(10) (3)(15)] = [5 20 45]

Page 12: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Matrix transpose operation – denoted by a prime symbol, ‘

x ‘ = [ 1 y = [5 10 15] 2 3 ]

For this vectors x and y matrix multiplication is

x ’* y = [ (1)(5) (1)(10) (1)(15) [ 5 10 15

(2)(5) (2)(10) (2)(15) = 10 20 30(3)(5) (3)(10) (3)(15) ] 15 30 15 ]

Page 13: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Polynomial Roots

In Matlab, one can define polynomials with an array whose elements are the polynomial coefficients. ExampleThe polynomial x^3-7x^2+40x-34 will be represented by the array [1,-7,40,-34]. The polynomial roots can be obtained with a root finding function hard coded in Matlab.>>a=[1,-7,40,-34];>>roots(a)ans=3.000+5.000i 3.000 -5.000i 1.000RemarksThe number of roots is equal to the order of the polynomialFor polynomials with real coefficients, the complex roots always occur in conjugate pairs.If we know the roots, the polynomial coefficients can be determined as:>>x=[1,3+5i,3-5i];>>poly(x)ans=1 -7 40 -34If you wish to evaluate the value of a polynomial for certain value of x, the following command achieves this:>> polyval(a,.8)ans= -5.9680

Polynomial additionLet f=[5,-7,9,11]; g=[6,0,3]; g=[0,g];f±g=[5±0,-7±6,9±0,11±3]; f+g →5x3-x2+9x+14

Product and Division of 2 PolynomialsLet f=[5,-7,9,11]; → 5x3-7x2+9x+11 g=[6,0,3]; →6x2+3>>conv(f,g)= [30,-42,69,45,27,33]; →30x5-42x4+69x3+45x2+27x+33

>>[q,r]=deconv(num,den)=f/g, where

Page 14: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

q=quotient=.8333, -1.1667 →.8333x-1.1667 r=remainder=0,-0,000,6.5,14.5→6.5x+14.5Check: f=conv(q,g)+rRemarkFor addition and subtraction, the polynomials must be of the same order. For multiplication or division the order of polynomials can be different.ExampleThe following equation appears in structural vibrations: (-f2)[(2-f2)2-2]+2f2-23=0 ,where is the natural frequency k/(42m) k=spring constant m=massClearly this equation can be treated in two different ways: (i) a cubic in f2, (ii) a 6th order equation. No matter how it is coded, the solution will be the same.(i) A cubic in f2=x→f= √x

p1=-x p2=2-x p3=2x-23

→p1[p22-2]+p3=0

Matlab code1>>p1=[-1,]; p2=[-1,2]; p3=[2,-23];>>p4=conv(p2,p2)-[0,0,2]; p5=conv(p1,p4)+[0,0,p3];>> rt=roots(p5); f1=sqrt(rt); f2=-sqrt(rt);(ii) Matlab Code 2 p1=[-1,0,]; p2=[-1,0,2]; p3=[2,0,-23]; >>p4=conv(p2,p2)-[0,0,0,0,2]; p5=conv(p1,p4)+[0,0,0,0,p3]; >> rt=roots(p5)Problems1. Find the roots of the following polynomial

13x3+182x2-184x+2053=0,use poly command to confirm your answer.

2. Find the roots of the polynomial36x3+12x2-5x+10=0use polyval command to confirm your answer.

3. Let the spring constant, k=4x106 Newtons/m and m=5000 kgWrite a Matlab code to find the roots of the 6th order equation given in the previous example.

Rational Operators

Page 15: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

< less than<= less than equal to

> greater than>= greater than equal to= = equal to~ = not equal to

Example>>x=[6,3,8];>>y=[12,1,9];>>z= (x<y)z = 1 0 1>>z= (x>y)z = 0 1 0>>z=(x ~ = y)z = 1 1 1>>z =(x = = y)z = 0 0 0Other Relational Operators>>z= x(x<y); finds all those x’s that are less than the corresponding elements of yExample>> x=[-2,0,4]>>y=find(x); identifies the nonzero elements of array xy=

1 3;The answer is that first and third elements of x are non zero>> x=[6,3,9,11]; y=[14,2,9,13];>>values=x(x<y)values=

6 11>>how_many=length(values)how_many= 2>>indices=find(x<y)

Page 16: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

indices= 1 4

Logical Expressions—if statements(a) If statements are commonly employed during programming.A good example is: if x>=0 y=sqrt(x); end(b) if (x>0)&(y>=0) z=sqrt(x)+sqrt(y); end(c) nested if statements

if(x>0) y=x^1.5 if(y<7) z=exp(.25*y) end endRemarkEach if statement has an accompanying end statement

else statementWhen more than one action occurs as a result of logical step, we use else or elseifExample(a) x=[1,-4,9,25]; if(x<0) disp(‘negative element of x’)else y=sqrt(x);end(b) if x>=5 y=log(x) else if(x>=0) y=sqrt(x) end end

Page 17: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

(c) in example (b) elseif statement can be used more efficientlyif(x>=5)y=log(x)elseif x>=0y=sqrt(x)endRemarkelseif statement does not require a separate end statement whereas else statement requires

Problems1. Write a script file to evaluate the following function: Y=ex+1 for x < -1; Y=2+cos(x) for –1 ≤ x ≤ 5; Y=10(x-5) +1 for >5 .

Evaluate y for x=-5, 3 and 15 and check your answer by hand.

LOOPSA loop is a structure for repeating a computation a number of times. Following three types of loops are usually used in Matlab.(i) Implied loopsFollowing statements contain implied loopsx=[0:.1:1];y=sin(pi*x);(ii) for-loops(a) for i=1:11 x = .1*(i-1); y=sin(pi*x);end(b) for i=1:1:11 x=.1*(I-1) y=sin(pi*x)end

In both (a) and (b) loop starts at i=1 and goes till 11 in steps of 1. The form (b) is a little more general. It can be used if the computations are say done at every three ‘i’ vales. Then the for statement will be: For i=1:3:11

(iii) while-loopsThis type of looping is used when the loop terminates due to a specified condition. So we do not know a priori the number of passes required to satisfy the condition.

Page 18: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

(a) x=2; while x<20 x=3x-1 endthe loop terminates when x becomes >= 20

(b) x=1 while x~=9 x=2x-1 endthe loop terminates when x~=9 is false for the first time

RemarksThe loop variable must have a value before while statement is executed.The statements must change the loop variable somehow.

Problems1. Use a while loop to determine how many terms in the series 2k ,

k=1,2,… are required for the sum to just exceed 1927.

Plot x-y plots

Ex.x y0 54.21 58.52 63.83 64.24 67.35 71.56 88.37 90.18 90.69 89.510 90.4

>> plot(x,y)title (‘Lab experiment #1’), xlabel (‘time,t’), ylabel (‘Temperature, degrees F’), grid

Page 19: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting
Page 20: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

(c) Hold on command

x = 0: .1 : piy1=cos(pi*x) RemarksPlot(x,y1), 2 plots on the same graphy2=sin(pi*x);hold on;plot(x,y2)

Page 21: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

(b) PlottingGraphs are generated by issuing the Matlab command

plot(x , y)

The following set of commands generates the graph below

x = 0 : 0.01 : 2 ; y = x^2 – 3plot(x , y); hold onxx = [0 2] ; yy = [0 0]plot(xx , yy) ; grid onhold off

Output

disp(variable)Displays the value of variable without the variable name

Page 22: Matlab Primer - University of Cincinnati · Web viewMatlab Primer Matlab is a programming language and also provides software environment for using the language effectively. Starting

Homework

A = 1 2 3 B = 1 0 2 4 5 6 2 1 0 7 8 7 0 3 1

i) Find A(3,3) and A(2,3)ii) Find detAiii) A + Biv) B + Av) A – Bvi) B – Avii) A * Bviii) B * Aix) A-1

x) A * A-1

xi) A-1 * A