matlab matlab lab manual numerical methods and matlab

15
MATLAB is a programming environment for algorithm development, data analysis, visualization, and numerical computation. Using MATLAB, we can solve technical computing problems faster than with traditional programming languages. Numerical Methods: Those are the methods by which mathematical problems are formulated so that they can be solved using arithmetic and logical operations. MATLAB provides a very nice tool to implement NUMERICAL METHODS. MATLAB can be employed to compute quantities and illustrate their graphical capabilities. Working in MATLAB: When we start MATLAB, the desktop appears in its default layout. MATLAB uses three primary windows : 1. Command Window-> Used to enter Commands and Data. 2. Graphics Window-> Used to Display plots and graphs. 3. Edit Window-> Used to create and edit m-files. Desktop’s default layout contains: • Command Window — Enter commands at the command line, indicated by the prompt (>>). • Workspace — The workspace contains variables that we create within or import into MATLAB from data files or other programs. • Command History — View or rerun commands that you entered at the command line. 1

Upload: javaria-chiragh

Post on 24-Oct-2015

273 views

Category:

Documents


13 download

DESCRIPTION

MATLABLab Manualgetting started in Matlabusing MATLAB in numerical methods and arithmetic operations working in matlabbasic functions of matlab how to use matlab in mathematicsplotting graphslab for matlabimplementation of numerical methods using matlab

TRANSCRIPT

Page 1: MATLAB  MATLAB lab manual  numerical methods and matlab

MATLAB is a programming environment for algorithm development, data analysis, visualization, and numerical computation.  Using MATLAB, we can solve technical computing problems faster than with traditional programming languages.

Numerical Methods:Those are the methods by which mathematical problems are formulated so that they can be solved using arithmetic and logical operations.MATLAB provides a very nice tool to implement NUMERICAL METHODS.MATLAB can be employed to compute quantities and illustrate their graphical capabilities.

Working in MATLAB:When we start MATLAB, the desktop appears in its default layout.MATLAB uses three primary windows :

1. Command Window-> Used to enter Commands and Data.2. Graphics Window-> Used to Display plots and graphs.3. Edit Window-> Used to create and edit m-files.

Desktop’s default layout contains:• Command Window — Enter commands at the command line, indicated by the prompt (>>).• Workspace — The workspace contains variables that we create within or import into MATLAB from data files or other programs.• Command History — View or rerun commands that you entered at the command line.

Matlab Basics: Variables and Assignment statements are used.

1

Page 2: MATLAB  MATLAB lab manual  numerical methods and matlab

There are many built-in functions in MATLAB Some of built-in functions are: abs( ), cos( ), exp( ), log( ), log10( ), sqrt( ), atan( ), etc.

The “reserved words” or “key words” or “name of built-in functions” are NOT to be used.

Expressions can be created using values, variables that have already been created, operators, built-in-functions, and parenthesis.

Echo printing means to perform operation but not show the results this is done by placing semi colon “;” at the end of statement.

M-files and Script files: M-Files and Script Files are used to execute a set of different

commends at a time. If needed, corrections or changes can be made to the commands in the file. The files that are used for this purpose are called script files or scripts for short.

A script file is an external file that contains a sequence of MATLAB statements. Script files have a filename extension .m and are often called M-files. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that can accept arguments and can produce one or more outputs.

Functions are programs (or routines) that accept input arguments and return output arguments. Each M-file function (or function or M-file for short) has its own area of workspace, separated from the MATLAB base workspace.

Basic Commands for working in MATLAB:Clc: Clears the commend window.Clear: remove all the variables from memory.Format short:Format long:%: used for comments.syms x: declare a symbolic variable x.

Arrays:A rectangular arrangement of numbers is called an array.

1-by-1 arrays are also called scalars 1-by-N arrays are also called row vectorsb= [1;2;3;4] It is s column vector or an array having four elements. N-by-1 arrays are also called column vectors

a= [1 2 3 4] It is a row vector or an array having four elements.

2

Page 3: MATLAB  MATLAB lab manual  numerical methods and matlab

Row and Column vectors are also sometimes just called vectors In Matlab, all arrays of numbers are called double arrays. If we say that Array is two or three dimensional it is called Matrix.

c= [1,2; 3,4] It is a 2 x 2 matrix or 2 x 2 array. sum( ) ,mean( ) , length( ) ,max( ) ,min( ) , prod( ) ,

sign( ) ,fix( ) ,floor( ) ,ceil( ) ,round( ) , sort( ) are some functions that can be used on matrices and arrays.

det( ) ,rank( ) ,trace( ) ,inv( ) , x=A\b ,poly( ) ,eig( ) , [v ,x]=eig(A) are the operations that are used on matrices.

Matrix Generator:1. zeros(p,q) Returns a matrix of all zeros of order pxq. 2. ones(p,q) Returns a matrix of all ones of order pxq.3. eye(p,q) Returns a matrix with ones on the main diagonal and zeros

elsewhere of order pxq.4. rand(n) ,rand(m, n) (chooses random entries from interval 0-1), rands(n),

rands(m, n) (chooses random entries from interval (-1,+1)), diag(v). Arithmetic operations can carried out on matrices provided that the operands

are compatible with the operations.

Working of Commands: Linspace:

linspace(x1, x2) generates a row vector of 100 linearly equally spaced points between x1 and x2.

linspace(x1, x2, n) generates n points between x1 and x2. For n < 2, linspace returns x2.

Example: x=linspace(0 , 10 , 3)

x =

0 5 10

Colon operator:X= x1: increment :x2 generates a row vector between x1 and x2 with increment.

Example:x= 9: -2 : 1

x = 9 7 5 3 1

polynomial:To declare a polynomial we generate vector and assign it to a variable Polyder: Gives the derivative of polynomial polyder(p).Polyint: Gives the integral of the polynomial polyint(p).Polyval: Evaluates the value of polynomial at any specific value of x

3

Page 4: MATLAB  MATLAB lab manual  numerical methods and matlab

Roots: find the roots of the polynomialPolyval(p , x).f= [ 1 2 3 4]>>f = 1 2 3 4>> polyder(f)ans = 3 4 3>> polyint(f)ans =

0.2500 0.6667 1.5000 4.0000 0>> polyval( f , 0)ans = 4

Fprintf: Writes formatted data to fileavg = 8>> fprintf ('the average is %f/n', avg)the average is 8.000000/n>>

String Functions:Sprintf: Writes formatted data to a stringsprintf( 'my name is %s \n' , s1)ans =my name is javariaStrcmp: compares two strings and returns 1 or 0 .Strmatch: matches two strings returns 1 or [].Findstr : finds one string in other and returns 1 or 0. s2 = 'javaria roll# 116's2 =javaria roll# 116>> s1 = 'javaria's1 =javaria>> strmatch (s1 , s2)ans = 1>> findstr( s1 , s2)ans = 1>> strcmp ( s1 , s2)ans = 0

Disp: simple commend used to display something.

4

Page 5: MATLAB  MATLAB lab manual  numerical methods and matlab

Plot: To create two-dimensional line plots, use the plot function. For example, plotthe value of the sine function from 0 to 2π:x = 0:pi/100:2*pi;y = sin(x);plot(x,y)xlabel('x')ylabel('sin(x)')title('Plot of the Sine Function')

Subplot: we can display multiple plots in different sub regions of the same window using the subplot function.

Example:Plots the following functions in interval0≤x≤2π using 100 points .use the subplotcommand to display these functions on fourwindows on same graph

Sin(x) Cos(x) Sin(x)*cos(x) Sin(x)/cos(x)

x= linspace ( 0 , 2*pi , 100);y=sin (x);subplot (2, 2, 1)plot ( x , y)z= cos (x);subplot ( 2, 2 , 2)plot ( x , z)w = sin (x).* cos(x);subplot ( 2 , 2 , 3)plot ( x , w)v = sin (x)./ cos(x);

5

Page 6: MATLAB  MATLAB lab manual  numerical methods and matlab

subplot ( 2, 2, 4)plot (x , v)

If statement: Conditional statements enable us to select at run time which block of code to execute. The simplest conditional statement is an if statement.

Example:Program which inputs marks and tells what grade is yoursx=input('Enter the marks')if (x>=90) disp (' your grade is A')else if (x>90) disp ('your grade is B') else if (x>80) disp('your grade is C') else if (x>70) disp ('your grade is D') else if (x>60) disp('your grade is F you are fail ') else disp ('') end end end endendans:

6

Page 7: MATLAB  MATLAB lab manual  numerical methods and matlab

Enter the marks77

x =

77

your grade is D

Switch:Switch statement Switchs among several cases based on expression.

Loop control:MATLAB functions that provide control overprogram loops.For loop:The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements.

Example:Program which gives the average of numbers using for loop:

7

Page 8: MATLAB  MATLAB lab manual  numerical methods and matlab

While loop:The while loop repeats a group of statements an indefinite number of timesunder control of a logical condition. A matching end delineates the statements.Continue: As it executes rest of commands in that loop are skippedand loop starts from begining.Break:it breaks the loop as it executes

Dsolve:We use ‘dsolve’ to find solution of ordinary differential equationsIts syntax is:r = dsolve('eq1,eq2,...', 'cond1,cond2,...', 'v')

Who and whos:Who: it lists all the current variables in use during a session.Whos: it also lists all current variables (long display) in use

8

Page 9: MATLAB  MATLAB lab manual  numerical methods and matlab

during a session

Backslash: The Matlab backslash operator solve linear systems of equations.

Example:We are going to compute the roots of the system of linear equations:X+2y+3z=14x+5y+6z=17x+8y=1>> a=[ 1 2 3 ; 4 5 6 ; 7 8 0 ]a = 1 2 3 4 5 6 7 8 0>> b= [1; 1 ; 1]b = 1 1 1>> x=a\bx = -1.0000 1.0000 -0.0000In this way backslash operator can be used.

Fzero: fzero can be used to solve a single variable nonlinear equation of the form f(x) = 0. Theequation must first be programmed as a function (either inline or m-file).

Example:x = fzero(fun,x0)fun is the function whose zero is to be computed.>>x = fzero('sin',3)x =3.1416

Realmax and realmin:Realmax is largest positive floating-point numberRealmin is smallest positive floating-point number>> realmaxans = 1.7977e+308>> realminans = 2.2251e-308

9

Page 10: MATLAB  MATLAB lab manual  numerical methods and matlab

Eps: eps is also known as Machine epsilon in MATLAB is the distance from 1 to the next valid floating point number..This value is used in determining the numerical rank of the matrix and in determining the pseudo inverse of a matrix.On an intel based machine>> epsans = 2.2204e-016

Tic & Toc:Used to calculate time duration of the process. Place tic before the code and toc after the code

Interpolation:For one dimensional interpolation interp1 commend is used there are basic five methods for linear interpolation.yi = interp1(x,Y,xi,method)is the basic syntax of the command

1. 'nearest'Nearest neighbor interpolation2. 'linear'Linear interpolation (default)3. Sunday, June 24, 2012'spline'Cubic spline interpolation4. 'pchip'Piecewise cubic Hermite interpolation5. 'cubic'(Same as 'pchip')'v5cubic'Cubic interpolation used in

MATLAB 5are the five methods used for linear interpolation.

Newton Raphson Method:

10

Page 11: MATLAB  MATLAB lab manual  numerical methods and matlab

Secent Method:

11

Page 12: MATLAB  MATLAB lab manual  numerical methods and matlab

Bisection Method:

12

Page 13: MATLAB  MATLAB lab manual  numerical methods and matlab

Vectorization:“Vectorization means converting for and while loops toequivalent vector or matrix operations”

13