Sie sind auf Seite 1von 58

Term-Work

1.Program on Roots of Equation (Validation by suitable solver, all four compulsory)


a). Bisection Method,
b). False position Method,
c). Newton Raphson method
d. Successive approximation method

2.Program on Simultaneous Equations (Validation by suitable solver, all three compulsory)


a)Gauss Elimination Method,
b)Thomas algorithm for tridiagonal matrix,
c)Gauss-Seidal method.

3.Program on Numerical Integration(Validation by suitable solver,all four compulsory)


a)Trapezoidal rule,
b)Simpson‟s Rules (1/3rd, 3/8th)
[In one program only] c)
Gauss Quadrature Method-
2 point, 3 point. [In one program only]
d)Double integration: Trapezoidal rule, S
impson‟s 1/3rdRule.

4.Program on Curve Fitting using Least square technique (Validation by suitable solver,all four
compulsory)
a)Straight line,
b)Power equation
c)Exponential equation
d)Quadratic equation

5.Program on Interpolation(Validation by suitable solver,all three compulsory)


a)Lagrange„s Interpolation,
b)Newton„s Forward interpolation,
c)Inverse interpolation
6.Program on ODE(Validation by suitable solver,all three compulsory)
a)Euler Method(Iterative),
b)Runge-Kutta Methods-fourth order,
c)Simultaneous equations.(Runge-Kutta 2nd order: One step only).

7.Program on PDE(Validation by suitable solver)


8.Theory assignment on ModernOptimization techniques.GUIDELINES TO CONDUCT
PRACTICAL EXAMINATION
Any one program from each set A & B with flowchart and solver: Duration: 2 hrs.
Set A:(Weightage –60 %)
a). Simultaneous Equation.
b).Partial Differential Equation
c).Interpolation.Set B:(Weightage –40 %)
a). Roots of Equations.
b).Curve Fitting.
c).Ordinary Differential Equations.
d).Integration

Text Books
1. Steven C. Chapra, Raymond P. Canale, Numerical Methods for Engineers, 4/e, Tata McGraw
Hill Editions
2. Dr. B. S. Garewal, Numerical Methods in Engineering and Science, Khanna Publishers,.
3. Steven C. Chapra, Applied N
umerical Methods with MATLAB for Engineers and Scientist, Tata
Mc-GrawHill Publishing Co-Ltd
4. Rao V. Dukkipati, Applied Numerical Methods using Matlab, New Age International Publishers
Reference Books
1. Gerald and Wheatley, Applied Numerical A
nalysis, Pearson Education Asia
2. E. Balagurusamy, Numerical Methods, Tata McGraw Hill
3. P. Thangaraj, Computer Oriented Numerical Methods, PHI
4. S. S. Sastry, Introductory Methods of Numerical Analysis, PHI.

Short introduction to Matlab


1 Getting started with Matlab

Matlab is a tool for mathematical (technical) calculations. First, it can be used as a scienti c
calculator. Next, it allows you to plot or visualize data in many di erent ways, perform matrix
algebra, work with polynomials or integrate functions. You can create, execute and save a
sequence of commands to make your computational process automatic. Finally, Matlab is also a
user-friendly programming language, which gives the possibility to handle mathematical
calculations in an easy way. In summary, as a computing/programming environment, Matlab is
especially designed to work with data sets as a whole such as vectors, matrices and images.
Therefore, PRTOOLS, a toolbox for Pattern Recognition purposes, and DIPLIB, a toolbox for
Image Processing, have been developed under Matlab.

On most systems, after logging in, you can enter Matlab with the system command matlab and
exit with the command exit or quit. Running Matlab creates one or more windows on your screen.
The most important is the Matlab Command Window , which is the place where you interact with
Matlab. The string >> (or EDU>> for the Student Edition) is the Matlab prompt. When the
Command window is active, a cursor appears after the prompt, indicating that Matlab is waiting
for your command.

1.1 Input via the command-line

Matlab is an interactive system; commands followed by Enter are executed immediately. The
results are, if desired, displayed on the screen. Execution of a command is only possible when
the command is typed according to the rules. Table 1 shows a list of commands used to solve
indicated mathematical equations (a, b, x and y are numbers). Below you nd basic information to
help you starting with Matlab :

Commands in Matlab are executed by pressing Enter or Return. The output will be
displayed on the screen immediately. Try the following:

>> 3 + 7.5

>> 18/4 - (3 * 7)

Note that spaces are not important in Matlab.

The result of the last performed computation is ascribed to the variable ans, which is an
example of a Matlab built-in variable. It can be used on the next command line. For
instance:

>> 14/
4 ans
=

3.5000

>> ans^(-6)
ans =

5.4399e-04

5.4399e-04 is a computer notation of 5:4399 10 4. Note that ans is always overwritten by the
last command.

You can also de ne your own variables (more on variables in section 2.1), e.g. a and b as:

>> a = 14/4

a=

3.5000
>> b = a^(-6)

b=

5.4399e-04

When the command is followed by a semicolon ';', the output is suppressed. Compare:

>> 3 + 7.5

>> 3 + 7.5;

It is possible to execute more than one command at the same time; the commands should
then be separated by commas (to display the output) or by semicolons (to suppress the
output display), e.g.:

>> sin(pi/4), cos(pi); sin(0)

ans =

0.7071

ans =

Note that the value of cos(pi) is not printed.


thematical notation Matlab command

a+b a+b

a b a-b
ab a*b

b a / b or b n a
x x^b

px sqrt(x) or x^0.5

jxj abs(x)
pi

4 103 4e3 or 4*10^3


i i or j

4i 3-4*i or 3-4*j

3 x

e, e exp(1), exp(x)
ln x, logx log(x), log10(x)

sin x, arctan x; ::: sin(x), atan(x),...

Table 1: Translation of mathematical notation to Matlab commands.

By default, Matlab displays only 5 digits. The command format long increases this number to
15, format short reduces it to 5 again. For instance:

>> 312/5
6 ans =

5.5714

>> format long

>> 312/56

ans =
5.57142857142857

The output may contain some empty lines; this can be suppressed by the command format
compact. In contrast, the command format loose will insert extra empty lines.
Matlab is case sensitive, for example, a is written as a in Matlab ; A will result then in an error.

All text after a percent sign % until the end of a line is treated as a comment. Enter e.g. the
following:

>> sin(3.14159) % this is an approximation of sin(pi)

You should skip comments while typing the examples.

Previous commands can be fetched back with the " -key. The command can also be
changed, the and ! -keys may be used to move around in a line and edit it.

1.2 help-facilities

Matlab provides assistance through extensive online help. The help command is the simplest way
to get help. It displays the list of all possible topics. To get a more general introduction to help, try:

>> help help

If you already know the topic or command, you can ask for a more speci ed help. For instance:

>> help elfun

provides information on the elementary math functions of Matlab. The topic you want help on
must be exact. The lookfor command is useful if you do not know the exact name of the
command or topic, e.g.:

>> lookfor inverse

displays a list of all commands, with a short description, for which the word inverse is included in
its help-text. Besides the help and lookfor commands, there is also a separate mouse driven help.
The helpwin command opens a new window on screen which can be browsed in an interactive
way.

1.3 Interrupting a command or program

Sometimes you might spot an error in your command or program. Due to this error it can happen
that the command or program does not stop. Pressing Ctrl-C (or Ctrl-Break on PC) forces Matlab
to stop the process. After this, the Matlab prompt (>>) re-appears. This may take a while, though.
1.4 Workspace issues

If you work in the Command Window, Matlab memorizes all commands that you entered and all
variables that you created. These commands and variables reside in the Matlab workspace and
they might be easily

recalled when needed, e.g. to recall previous commands, the " -key is used. Variables can be veri ed with the
commands who, which gives a list of variables present, and whos, which includes also extra information.
Assuming that you performed all commands given in section 1.1, after typing who you would obtain:

>> who

Your variables are:

a ans b x

The command clear <name> deletes the variable <name> from the Matlab workspace, clear or
clear all removes all variables. This is useful when starting a new task. For example:

>> clear a x

>> who

Your variables are:


ans b

1.5 Saving and loading data

The easiest way to save or load Matlab variables is by using (clicking) the File menu-bar, and
then the Save Workspace as... and Load Workspace... items. Alternatively, the Matlab
commands save and load can be used. save allows for saving your workspace variables either
into a binary le or an ASCII le. Binary les automatically get the '.mat' extension. For ASCII les, it is
recommended to add a '.txt' or '.dat' extension. Study the use of the save command:

>> s1 = sin(pi/4);

>> c1 = cos(pi/4); c2 = cos(pi/2);

>> str = 'hello world'; % a string


>> save data % saves all variables in binary format to data.mat

>> save numdata s1, c1% saves numeric variables: s1 and c1 to numdata.mat

>> save allcos.dat c* -ascii % saves c1,c2 in 8-digit ascii format to allcos.dat

The load command allows for loading variables into the workspace. It uses the same syntax as save. It might be
useful to clear the workspace before each load and check which variables are present in the workspace (use
who) after loading. Assuming that you have created the les above, the variables can be now loaded as:
>> load data % loads all variables from data.mat
>> load data s1 c1 % loads only specified variables from data.mat

It is also possible to read ASCII les that contain rows of space separated values. Such a le may
contain comments that begin with a percent character. The resulting data is placed into a variable
with the same name as the ASCII le (without the extension). Check, for example:

>> load allcos.dat % loads data from the file allcos.dat into variable allcos
>> who % lists variables present in the workspace now

2 Mathematics with vectors and matrices

The basic element of Matlab is a matrix (or an array). Special cases are:

a 1 1-matrix: a scalar or a single number;

a matrix existing only of one row or one column: a vector.

Note that Matlab may behave di erently depending on input, whether it is a number, a vector or a
2D matrix.

2.1 Assignments and variables

Formally, there is no need to declare (i.e. de ne the name, size and the type of) a new variable in
Matlab. A variable is simply created by an assignment (e.g. a = 15/4). Each newly created
numerical variable is always of the double type. You can change this type by converting it into
e.g. the single type1.

1
a variable a is converted into a di erent type by performing e.g. a = single(a), etc.
Value/meaning

the default variable name used for storing the last result

= 3:14159:::

the smallest positive number that added to 1, creates a result larger


than 1

representation for positive in nity, e.g. 1/0

representation for not-a-number, e.g. 0/0


p

i = j =1
number of function input/output arguments used

the smallest/largest usable positive real number

Table 2: Built-in variables in Matlab.

Bear in mind that unde ned values cannot be assigned to a variable. So, the following is not
possible:

>> clear x; % to make sure that x does not exist

>> f = x^2 + 4 * sin (x)

It becomes possible by:

>> x = pi / 3; f = x^2 + 4 * sin (x)

Here are some examples of di erent types of Matlab variables (check their types by using whos):

>> M = [1 2; 3 4; 5 6] % a matrix
>> 2t = 8 % what is the problem with this command?
>> c = 'E' % a character
>> str = 'Hello world' % a string

There is also a number of built-in variables, e.g. pi, eps or i, presented in Table 2. In addition to
creating variables by assigning values to them, another possibility is to copy one variable, e.g. b
into another, e.g. a. In this way, the variable a is automatically created (if a already existed, its
previous value is now lost):

>> b = 10.5;

>> a = b;
If min is the name of a function (see section 4.2), then a de ned as:

>> b = 5; c = 7;

>> a = min (b,c);

will call that function, with the values b and c as parameters. The result of this function (its return
value) will be written (assigned) into a.

2.2 Vectors

Row vectors are lists of numbers separated either by commas or by spaces. They are examples of simple arrays. First
element has index 1. The number of entries is known as the length of the vector (the command length exists as well).
Their entities are referred to as elements or components. The entries must be enclosed in [ ]:

>> v = [-1 sin(3) 7] v


=

-1.0000 0.1411 7.0000

A number of operations can be performed on vectors. A vector can be multiplied by a scalar, or


added/subtracted to/from another vector with the same length, or a number can be
added/subtracted to/from a vector. A particular value can be also changed or displayed. All these
operations are carried out element-by-element. Vectors can be also built from the already existing
ones:

>> v = [-1 2 7]; w = [2 3 4];

>> z = v + w % an element-by-element sum

z=

1 5 11

>> t = [2*v, -w+2]

ans =
-2 4 14 0 -1 -2
% change the 2nd element of
>> v(2) = -1 v

v=

-1 -1 7
A colon notation is an important shortcut, used when producing row vectors (see Table 3 and help
colon):

>> 2:5

ans =
2 3 4 5

In general, first:step:last produces a vector of entities with the value first, incrementing by the step
until it reaches last:

>> -0.2:0.5:1.7

ans =

-0.2000 0.3000 0.8000 1.3000

>> 5.5:-2:-2.5 % a negative step is also possible

ans =
5.5000 3.5000 1.5000 -0.5000 -2.5000

Parts of vectors can be extracted by using a colon notation:

>> r = [-1:2.5:6, 2, 3, -2]; % r = [-1 1.5 4 2 3 -2]

>> r(2:2:6) % get the elements of r from the positions 2, 4 and 6

ans =

1.5 2 -2

To create column vectors, you should separate entries by a semicolon ';' or by new lines. The
same operations as on row vectors can be done on column vectors. However, you cannot for
example add a column vector to a row vector. To do that, you need an operation called
transposing, which converts a column vector into a row vector and vice versa:

>> f = [-1; 3; 5] % a column vector

f=

-1

>> f' % f' is a row vector

ans =

-1 3 5

>> v = [-1 2 7]; % a row vector


>> f + v % you cannot add a column vector f to a row vector v

??? Error using ==> +

Matrix dimensions must agree.

>> f' + v

ans =

-2 5 12
is P

You can now compute the inner product between two vectors x and y,
xT y = i xi yi, in a simple way:

>> v = [-1; 2; 7]; % v is now a column vector; f also a column vector

>> f' * v % this is the inner product! f * v' is the outer product

ans =

42

2.3 Matrices

An n k matrix is a rectangular array of numbers having n rows and k columns. De ning a matrix in
Matlab is similar to de ning a vector. The generalization is straightforward, if you know that a
matrix consists of row vectors (or column vectors). Commas or spaces are used to separate
elements in a row, and semicolons are used to separate individual rows. For example, a matrix
can be de ned as:

>> A = [1 2 3; 4 5 6; 7 8 9] % row by row input

A=
1 2 3
4 5 6
7 8 9

Transposing a vector changes it from a row to a column or the other way around. This idea can be extended to a
matrix, where transposing interchanges rows with the corresponding columns, as in the example:

5
Command Result

A(i,j) Aij
A(:,j) j-th column of A

A(i,:) i-th row of A

A(k:l,m:n) (l k + 1) (n m + 1) matrix with elements Aij with k i l, m j n

v(i:j)' 'vector-part' (vi, vi+1, . . . , vj ) of vector v

Table 3: Manipulation of (groups of) matrix elements.

Command Result

n = rank(A) n becomes the rank of matrix A

x = det(A) x becomes the determinant of matrix A

x becomes a row-vector with 2 elements: the number of rows and


x = size(A) columns of A

x = trace(A) x becomes the trace (sum of diagonal elements) of matrix A

x = norm(v) x becomes the Euclidean length of vector v

C=A+B sum of two matrices

C=A-B subtraction of two matrices

C=A*B multiplication of two matrices

C = A .* B 'element-by-element' multiplication (A and B are of equal size)

C=A^k power of a matrix (k 2 Z; can also be used for A 1)

C = A .^ k 'element-by-element' power of a matrix

C = A' the transposed of a matrix; AT

C = A ./ B 'element-by-element' division (A and B are of equal size)


nds the solution in the least squares sense to the system of equations AX
X=AnB =B
X=B/A nds the solution of XA = B, analogous to the previous command

C = inv(A) C becomes the inverse of A

C is an orthonormal basis for the null space of A obtained from the


C = null(A) singular

value decomposition

C = orth(A) C is an orthonormal basis for the range of A

C = rref(A) C is the reduced row echelon form of A

L is a vector containing the (possibly complex) eigenvalues of a square


L = eig(A) matrix A

produces a diagonal matrix D of eigenvalues and a full matrix X whose


[X,D] = eig(A) columns

are the corresponding eigenvectors of A

S = svd(A) S is a vector containing the singular values of A

S is a diagonal matrix with nonnegative diagonal elements in decreasing


[U,S,V] = svd(A) order;

columns of U and V are the accompanying singular vectors

x = linspace(a,b,n) generates a vector x of n equally spaced points between a and b

x = logspace(a,b,n) generates a vector x starting at 10a and ended at 10b containing n values

A = eye(n) A is an n n identity matrix


A = zeros(n,m) A is an n m matrix with zeros (default m = n)
A = ones(n,m ) A is an n m matrix with ones (default m = n)

A = diag(v) gives a diagonal matrix with the elements v1; v2; : : : ; vn on the diagonal

X = tril(A) X is lower triangular part of A

X = triu(A) X is upper triangular part of A

A = rand(n,m) A is an n m matrix with elements uniformly distributed between 0 and 1


A = randn(n,m) ditto - with elements standard normal distributed

v = max(A) v is a vector with the maximum value of the elements in each column of A
or v is the maximum of all elements if A is a vector

v = min(A) ditto - with minimum

v = sum(A) ditto - with sum

Table 4: Frequently used matrix operations and functions.


>> A2 = [1:4; -1:2:5], A2' A2
=

1 2 3 4
-1 1 3 5

ans =

1 -1

2 1

3 3

4 5

>> size(A2), size(A2') % returns the size (dimensions) of a matrix

ans =

2 4

ans =

4 2

There are also built-in matrices of size speci ed by the user (see Table 4). A few examples are
given below:

>> I = eye(2) % the 2-by-2 identity matrix

I=

1 0

0 1

>> B = randn(1,2) % a vector of normally distributed random numbers

B=

-0.4326 -1.6656
>> r = [1 3 -2]; R = diag(r) % create a diagonal matrix with r on the diagonal

R=

1 0 0

0 3 0

0 0 -2
It is often needed to build a larger matrix from the smaller ones:
>> x = [4; -1]; y = [-1 3]; X = [x y']
%
X= X consists of the columns: x and y'

4 -1

-1 3
>> T = [-1 3 4; 4 5 6]; t = 1:3;
>> A = [T; t ones(3,2)] % add a row vector t, then add two columns of 1's at the end

A=

-1 3 4 1 1

4 5 6 1 1

1 2 3 1 1

It is possible to manipulate (groups of) matrix elements (see Table 3). A part can be extracted
from a matrix in a similar way as from a vector. Each element in the matrix is indexed by a row
and a column to which it belongs, e.g. A(i,j) denotes the element from the i-th row and the j-th
column of the matrix A.

>> A(3,4)

ans =

1
>> A(4,3) % A is a 3-by-5 matrix! A(4,3) does not exist

??? Index exceeds matrix dimensions.

It is easy to extend a matrix automatically. For the matrix A it can be done e.g. as follows:,
>> A(4,3) = -2 % assign -2 to the position (4,3); the uninitialized

A= % elements become zeros


-1 3 4 1 1

4 5 6 1 -1
1 2 3 1 1
0 0 -2 0 0
>> A(4,[1:2,4:5]) = 4:7; % assign: A(4,1) = 4, A(4,2) = 5, A(4,4) = 6 and A(4,5) = 7

Di erent parts of the matrix A can be now extracted:


>> A(:,2) % extract the 2nd column of A; what will you get here?

>> A(4,:) % extract the 4th row of A

ans =
4 5 -2 6 7

>> A(2:3,[1,5])

4 -1

1 1

Table 4 shows some frequently used matrix operations and functions. A few examples are given
below:

>> B = [1 4 -3; -7 8 4]; C = [1 2; 5 1; 5 6];


>> (B + C')./4 % add matrices and divide all elements of the result by 4

ans =
0.5000 2.2500 0.5000
-1.2500 2.2500 2.5000
>> D = [1 -1 4; 7 0 -1];
>> D = B * D'; D^3 % D^3 is equivalent to D * D * D

ans =

-4205 38390

3839 -150087

>> D.^3 - 2 % do for all elements: raise to the power 3 and subtract 2

ans =

-3377 998

-1 -148879

The concept of an empty matrix [] is also very useful in Matlab. For instance, a few columns or
rows can be removed from a matrix by assigning an empty matrix to it. Try for example:

>> C = [1 2 3 4; 5 6 7 8; 1 1 1 1];

now a
>> D = C; D(:,2) = [] % copy of C is in D; remove the 2nd column of D
remove
>> C ([1,3],:) = [] % the 1st and 3rd rows from C

3 Control ow
A control ow structure is a block of commands that allows conditional code execution and making loops.

3.1 Logical and relational operators

To use control ow commands, it is necessary to perform operations that result in logical values:
TRUE or FALSE, which in Matlab correspond to 1 or 0 respectively (see Table 5 and help relop).
The relational operators <, <=, >, >=, == and ~= can be used to compare two arrays of the same
size or an array to a scalar. The logical operators &, | and ~ allow for the logical combination or
negation of relational operators. The logical & and | have equal precedence in Matlab, which
means that those operators associate from left to right. In addition, three functions are also
available: xor, any and all (use help to nd out more).

Command Result

a is 1 if b is larger than c. Similar are: <, >= and


a = (b > c) <=

a = (b == c) a is 1 if b is equal to c

a = (b ~= c) a is 1 if b is not equal c

a = ~b logical complement: a is 1 if b is 0

a = (b & c) logical AND: a is 1 if b = TRUE AND c = TRUE

a = (b | c) logical OR: a is 1 if b = TRUE OR c = TRUE

Table 5: Relational and logical operations.

3.1.1 The command find

You can extract all elements from the vector or the matrix satisfying a given condition, e.g. equal
to 1 or larger than 5, by using logical addressing. The same result can be obtained via the
command find, which return the positions (indices) of such elements. For instance:
>> x = [1 1 3 4 1];

>> i = (x == 1)
i=
1 1 0 0 1

>> j = find(x == 1) % j holds indices of the elements satisfying x == 1

j=

1 2 5

>> y = x(i), z = x(j) y =

1 1 1

z=

1 1 1

find operates in a similar way on matrices. It reshapes rst the matrix A into a column vector, i.e. all
columns all concatenated one after another. Therefore, e.g. k = find (A > 2) is a list of indices of
elements larger than 2 and A(k) gives the values. The row and column indices can be returned by
[I,J] = find (A > 2).

3.2 Conditional code execution

Selection control structures, if-blocks, are used to decide which instruction to execute next
depending whether expression is TRUE or not. The general description is given below. In the
examples below the command disp is frequently used. This command displays on the screen the
text between the quotes.

if ... end

Syntax Example

if logical_expression if (a > 0)

statement1 b = a;

statement2 disp ('a is positive');

.... end
end

if ... else ... end


Syntax Example

if logical_expression if (temperature > 100)


block of statements disp ('Above boiling.');

evaluated if TRUE toohigh = 1;

else else

block of statements disp ('Temperature is OK.');

evaluated if FALSE toohigh = 0;

end end

if ... elseif ... else ... end


Syntax Example

if logical_expression1 if (height > 190)

block of statements evaluated disp ('very tall');

if logical_expression1 is TRUE elseif (height > 170)

elseif logical_expression2 disp ('tall');

block of statements evaluated elseif (height < 150)

if logical_expression2 is TRUE disp ('small');

else else

block of statements evaluated disp ('average');

if no other expression is TRUE end


end

Another selection structure is switch, which switches between several cases depending on an
expression, which is either a scalar or a string. Learn more by using help.
3.3 Loops

Iteration control structures, loops, are used to repeat a block of statements until some
condition is met: the for loop that repeats a group of statements a xed number of times;

Syntax Example

for index = first:step:last sumx = 0;

block of statements for i=1:length(x)

end sumx = sumx + x(i);


end

You can specify any step, including a negative value. The index of the for-loop can be also a
vector. See some examples of possible variations:

Example 1 Example 2 Example 3 Example 4

for i=1:2:n for i=n:-1:3 for x=0:0.5:4 for x=[25 9 81]

... .... disp(x^2); disp(sqrt(x));

end end end end

while loop, which evaluates a group of commands as long as expression is TRUE.

Syntax Example

while expression N = 100;

statement1 iter = 1;

statement2 msum = 0;

statement3 while iter <= N

... msum = msum + iter;

end iter = iter + 1;


end;

4 Script and function m- les

4.1 Script m- les


Script m- les are useful when the number of commands increases or when you want to change
values of some variables and re-evaluate them quickly. Formally, a script is an external le that
contains a sequence of Matlab commands. However, it is not a function, since there are no
input/output parameters and the script variables remain in the workspace. When you run a
script, the commands in it are executed as if they have been entered through the
keyboard. To create a script, open the Matlab editor (go to the

File menu-bar, choose the Open option and then m- le; the Matlab Editor Window will appear),
enter the lines listed below and save as sinplot.m:

x = 0:0.2:6; y = sin(x); plot(x,y);


title('Plot of y = sin(x)');

The script can be run by calling sinplot. Note that m-script le must be saved in one of the
directories in Matlab's path. The sinplot script a ects the workspace. Check:

>> clear % all variables are removed from the workspace

>> who % no variables present


>> sinplot % run the script

>> who

Your variables are:

x y

These generic names, x and y, may be easily used in further computations and this can cause
side e ects. They occur, in general, when a set of commands change variables other than the
input arguments. Remember that the commands within a script have access to all variables in the
workspace and all variables created in this script become a part of the workspace. Therefore, it is
better to use function m- les (see section 4.2) for a speci c problem to be solved.
4.2 Function m- le
Functions m- les are true subprograms, as they take input arguments and/or return output parameters. They can
call other functions, as well. Variables de ned and used inside a function, di erent from the input/output
arguments, are invisible to other functions and to the command environment. The general syntax is:

function [outputArgs] = function_name (inputArgs)

outputArgs are enclosed in [ ]:

{ a comma-separated list of variable names;

{ [ ] is optional when only one argument is


present; { functions without outputArgs are
legal2.

inputArgs are enclosed in ( ):

{ a comma-separated list of variable names; {


functions without inputArgs are legal.

Matlab provides a structure for creating your own functions. The rst line should be a de nition of a new function
(called a header). After that, a continuous sequence of comment lines, explaining what the function does, should
appear. Since they are displayed in response to the help command, also the expected input parameters, returned
output parameters and synopsis should be described there. Finally, the remainder of the function is called the
body. Function m- les terminate execution when they reach the end of the le or, alternatively, when the
command return is encountered. The name of the function and the name of the le stored should be identical . As
an example, the function average, stored in a le average.m, is de ned as:

output argument function name


input argument

the first line must be

function avr = average (x)


the function definition

%AVERAGE computes the average value of a vector x

comment % and returns it in avr

% Notes: an example of a function

n = length(x); a blank line within the comment;

avr = sum(x)/n; Notes information will NOT appear


function body
when you ask: help average
return;
Here is an another example of a function:

function [avr,sd] = stat(x)

%STAT Simple statistics; computes the average and the standard deviation of a vector
x. n = length(x);

avr = sum(x)/n;

sd = sqrt(sum((x -
avr).^2)/n); return;

Warning: The functions mean and std already exist in Matlab. As long as a function name is
used as a variable name, Matlab can not perform the function. Many other, easily appealing
names, such as sum or prod are reserved by Matlab functions, so be careful when choosing
your names.

When controlling the proper use of parameters, the function error may become useful. It
displays an error message, aborts function execution, and returns to the command
environment. Here is an example:

if (a >= 1)

error ('a must be smaller than


1'); end;

4.3 Scripts vs. functions

The most important di erence between a script and a function is that all script's parameters
and variables are externally accessible (i.e. in the workspace), where function variables are
not. Therefore, a script is a good tool for documenting work, designing experiments and
testing. In general, create a function to solve a given problem for arbitrary parameters; use a
script to run functions for speci c parameters required by the assignment.
1. Program on Roots of Equation (Validation by suitable solver, all four compulsory)

A). Bisection Method,

Matlab Program
x1=input('\nEnter first initial guess:');

x2=input('\nEnter second initial guess:');

e=input('\nEnter accuracy:');

n=input('\nEnter number of iteration:');

s=input('\nEnter F(x)=','s');

f=inline(s);

while(f(x2)*f(x1)>0)

x1=input('\nEnter first initial guess:');

x2=input('\nEnter second initial guess:');

end

i=1;

x3=x2;

while(i<=n & abs(f(x3))>e)

x3=(x1+x2)/2;

if(f(x1)*f(x3)<0)

x2=x3;

else

x1=x3;

end

i=i+1;

end

fprintf('Approximate Root of equation is %f',x3);


Output

Enter first initial guess:0.5

Enter second initial guess:1

Enter accuracy:0.01

Enter number of iteration:3

Enter F(x)=(cos (x)-1.3*x)

Approximate Root of equation is 0.621094>>


B)False position method

MATIAB PROGRAM

f=inline('(exp(x)*cos(x)-1.2*sin(x)-.5)');
x1=input('\n Enter value of initial guess x1= ');
x2=input('\n Enter value of initial guess x2= ');
acc=input('\n Enter acc= ');
y1=f(x1);
y2=f(x2);
while(y1*y2>0)
x1=input('\n Enter value of initial guess x1= ');
x2=input('\n Enter value of initial guess x2= ');
y1=f(x1);
y2=f(x2);
end
while(abs(x2-x1)>acc)
x3=(x2*y1-x1*y2)/(y1-y2);
y3=f(x3)
if(y1*y3<0)
x2=x3;
y2=y3;
else
x1=x3;
y1=y3;
end
end
x3=(x2*y1-x1*y2)/(y1-y2)
fprintf ('\n The root of equation is = %f',x3);

OUTOUT

Enter value of initial guess x1= 0

Enter value of initial guess x2= 1

Enter acc= 0.03

y3 = 0.0605

y3 =0.0023

y3 =8.1375e-005

x3 = 0.9710

The root of equation is = 0.970999>>


C) Newton Raphson Method

MATLAB PROGRAM

f=inline('(x*x*x-5*x+3)');
df=inline('(3*x*x-5)');
ddf=inline('(6*x)');
x1=input('\n Enter value of initial guess x1=');
n=input('\n Enter number of iterations=');
y1=f(x1);
y2=df(x1);
y3=ddf(x1);
a=(y1*y3)/(y2*y2);
while(abs(a)>1)
x1=input('\n Enter value of new guess x1=');
y1=f(x1);
y2=df(x1);
y3=ddf(x1);
a=(y1*y3)/(y2*y2);
end
for i=1:n
x2=x1-(y1/y2);
x1=x2;
y1=f(x1);
y2=df(x1);
end
fprintf('\n The root of equationis=%f',x2);

Output

Enter value of initial guess x1=0

Enter number of iterations=3

The root of equationis=0.656619>>


D)Successive Approximation Method

MATLAB PROGRAM

g=inline('(1+0.3*cos(x))');
dg=inline('(-0.3*sin(x))');
x1=input('\n Enter value of initial guess x1=');
n=input('\n Enter number of iterations=');
a=dg(x1);
while(abs(a)>1)
fprintf('\n Enter again value of initial guess x1=');
n=dg(x1);
end
for i=1:n
x2=g(x1);
x1=x2;
end
fprintf('\n The root of equationis=%f',x2);

Output

Enter value of initial guess x1=1

Enter number of iterations=4

The root of equationis=1.127750


2. Program on Simultaneous Of Equation (Validation by suitable solver, all four
compulsory)

A)Gauss Elimination Method

MATLAB PROGRAM

n=input('\nEnter the no. of equations = ');


for i=1:1:n
for j=1:1:n
a(i,j)=input('a');
end
a(i,n+1)=input('b');
x(i)=0;
end
for k=1:1:n
for i=k+1:1:n
ratio=a(i,k)/a(k,k);
for j=k+1:1:n+1
a(i,j)=a(i,j)-ratio*a(k,j);
end
end
for i=k+1:1:n
a(i,k)=0;
end
end
x(n)=a(n,n+1)/a(n,n);
for i=n-1:-1:1
coefsum=0;
for j=i+1:1:n
coefsum=coefsum+a(i,j)*x(j);
x(i)=(a(i,n+1)-coefsum)/a(i,i);
end
end
fprintf('\nThe values of variables are= ');
for i=1:1:n
fprintf('\n %3.4f',x(i));
end
OUTPUT
Enter the no. of equations i= 3
a12
a-2
a3
b18
a1
a10
a-2
b16
a3
a1
a15
b52
The values of variables are=
x1=1.0748
x2=2.1147
x3=3.1107>>
B)Thomas Algorithm For Tridiagonal Matrix

MATLAB PROGRAM

n=input('\n Enter number of equations: ');


for i=1:n
for j=1:n
a(i,j)=input('\n Enter matrix element: ');
end
b(i,1)=input('\n Enter constant: ');
end
for i=2:n
fact=a(i,i-1)/a(i-1,i-1);
for j=1:n
a(i-1,j)=a(i-1,j)*fact;
end
b(i-1)=b(i-1)*fact;
for j=1:n
a(i,j)=a(i,j)-a(i-1,j);
end
b(i)=b(i)-b(i-1);
end
for i=1:n
dig=a(i,i);
for j=1:n
a(i,j)=a(i,j)/dig;
end
b(i)=b(i)/dig;
end
res(n)=b(n);
for i=n-1:-1:1
res(i)=b(i);
for j=i:n-1
res(i)=res(i)-res(j+1)*a(i,j+1);
end
end
for i=1:n
fprintf('\n Value of x%d =%f',i,res(i));
end
OUTPUT

Enter number of equations: 4

Enter matrix element: 3

Enter matrix element: -1

Enter matrix element: 0

Enter matrix element: 0

Enter constant: 1

Enter matrix element: -1

Enter matrix element: 3

Enter matrix element: -1

Enter matrix element: 0

Enter constant: 7

Enter matrix element: 0

Enter matrix element: -1

Enter matrix element: 3

Enter matrix element: -1

Enter constant: 5

Enter matrix element: 0

Enter matrix element: 0

Enter matrix element: -1

Enter matrix element: 3

Enter constant: 18

Value of x1 =2.000000
Value of x2 =5.000000
Value of x3 =6.000000
Value of x4 =8.000000>>
C) Gauss-seidal method

MATLAB PROGRAM

n=input('\n Enter number of equation : ');


for i=1:n
for j=1:n
a(i,j)=input('\n Enter Matrics Element :')
end
b(i,1)=input('\n Enter Constant :');
end
nit=input('\n Enter number of iterations : ');
for i=1:n
x(i)=0;
end
for k=1:nit
fprintf('\n Iteration number : %d\n',k);
for i=1:n
val=b(i);
for j=1:n
if(i~=j)
val=val-a(i,j)*x(j);
end
end
x(i)=val/a(i,i);
fprintf('X%d = %f\n',i,x(i));
end
end

OUTPUT

Enter number of equation : 3

Enter Matrics Element :5

a=5

Enter Matrics Element :4

a=5 4

Enter Matrics Element :10

a=5 4 10

Enter Constant :2

Enter Matrics Element :0

a=5 4 10

0 0 0
Enter Matrics Element :5

a=5 4 10

0 5 0

Enter Matrics Element :2

a=5 4 10

0 5 2

Enter Constant :3

Enter Matrics Element :4

a=5 4 10

0 5 2

4 0 0

Enter Matrics Element :0

a=5 4 10

0 5 2

4 0 0

Enter Matrics Element :2

a=5 4 10

0 5 2

4 0 2

Enter Constant :4

Enter number of iterations : 5

Iteration number : 1
X1 = 0.400000

X2 = 0.600000

X3 = 1.200000

Iteration number : 2

X1 = -2.480000

X2 = 0.120000

X3 = 6.960000

Iteration number : 3

X1 = -13.616000

X2 = -2.184000

X3 = 29.232000

Iteration number : 4

X1 = -56.316800

X2 = -11.092800

X3 = 114.633600

Iteration number : 5

X1 = -219.992960

X2 = -45.253440

X3 = 441.985920
3. Program on Numerical Intigration (Validation by suitable solver, all four
compulsory)

A) Trapezoidal Rule

MATLAB PROGRAM

f=inline('(2*x-x*x)');
x0=input('Enter value of lower limit x0 :');
xn=input('Enter value of upper limit xn :');
n=input('Enter the number of strips :');
h=(xn-x0)/n;
res=0;
for i=1:n-1
res=res+(f(x0+i*h));
end
res=2*(res);
temp=f(x0)+f(xn);
area=(h/2)*(res+temp);
fprintf('Total area under the curve= %f',area);

Output

Enter value of lower limit x0 :0

Enter value of upper limit xn :3

Enter the number of strips :6

Total area under the curve= -0.125000


B1) Simpson (1/3)Rd Rule

MATLAB PROGRAM

f=inline('(exp(x)/x)');

x0=input('Enter value of lower limit x0 =');

xn=input('Enter value of upper limit xn =');

n=input('Enter the number of strips =');

while(mod(n,2)~=0)

n=input('Enter the number of strips again =');

end

h=(xn-x0)/n;

res=0;

for i=1:n-1

if(mod(i,2)~=0)

res=res+4*f(x0+i*h);

else

res=res+2*f(x0+i*h);

end

end

temp=f(x0)+f(xn);

area=(h/3)*(res+temp);

fprintf('Total area under the curve =%f',area);

Output

Enter value of lower limit x0 =1

Enter value of upper limit xn =2

Enter the number of strips =6

Total area under the curve =3.059142


B2) Simpson (3/8)Rd Rule

MATLAB PROGRAM
f=inline('(sin(x)/(2+3*sin(x)))');
x0=input('Enter value of lower limit x0 =');
xn=input('Enter the value of upper limit xn=');
n=input ('Enter the number of strips =');
while (mod(n,3)~=0)
n=input('Enter the number of strips again=');
end
h=(xn-x0)/n;
res=0;
for i=1:n-1
if(mod(i,3)~=0)
res=res+3*f(x0+i*h);
else res=res+2*f(x0+i*h);
end
end
temp=f(x0)+f(xn);
area=(3*h/8)*(res+temp);
fprintf('Total area under the curve=%f',area);

Output

Enter value of lower limit x0 =0

Enter the value of upper limit xn=1

Enter the number of strips =6

Total area under the curve=0.125042


C1)Guess-Legendre Two Point Method

MATLAB PROGRAM
f=inline('(exp(-x/2))');
x0=input('Enter value of lower limit x0=');
xn=input('Enter value of upper limit xn=');
c=(xn-x0)/2;
d=(xn+x0)/2;
x1=(c/sqrt(3))+d;
x2=(-c/sqrt(3))+d;
y1=f(x1);
y2=f(x2);
area=(y1+y2)*c;
fprintf('Total area under the cure =%f',area);

Output

Enter value of lower limit x0=-2


Enter value of upper limit xn=2
Total area under the cure =4.685392>>
C2)Guess-Legendre Three Point Method

MATLAB PROGRAM
f=inline('(exp(x)*cos(x)-2*x)');
x0=input('Enter value of lower limit x0=');
xn=input('Enter value of upper limit xn=');
c=(xn-x0)/2;
d=(xn+x0)/2;
x1=(c*sqrt(3/5))+d;
x2=(-c*sqrt(3/5))+d;
x3=d;
y1=f(x1);
y2=f(x2);
y3=f(x3);
area=((5/9)*(y1+y2)+(8/9)*(y3))*c;
fprintf('Total area under the cure =%f',area);

Output

Enter value of lower limit x0=0


Enter value of upper limit xn=1
Total area under the cure =0.378021>>
D1)Double Intigration By Trapezoidal Rule

MATLAB PROGRAM
f=inline('(exp(x+y))');
x0=input('Enter value of lower limit of first itegration =');
xn=input('Enter value of upper limit of first itegration =');
y0=input('Enter value of lower limit of second itegration =');
ym=input('Enter value of upper limit of second itegration =');
n=input('Enter the number of strips for x= ');
m=input('Enter the number of strips for y= ');
h=(xn-x0)/n;
k=(ym-y0)/m;
temp=x0;
for i=1:m+1
x0=temp;
for j=1:n+1
a(i,j)=f(x0,y0);
x0=x0+h;
end
y0=y0+k;
end
disp(a);
ans=0;
for i=1:m
for j=1:n
ans=ans+a(i,j)+a(i,j+1)+a(i+1,j)+a(i+1,j+1);
end
end
area=((h/2)*(k/2))*ans;
fprintf('Total area under the curve =%f',area);

Output

Enter value of lower limit of first itegration =0


Enter value of upper limit of first itegration =1
Enter value of lower limit of second itegration =0
Enter value of upper limit of second itegration =1
Enter the number of strips for x= 2
Enter the number of strips for y= 2
1.0000 1.6487 2.7183
1.6487 2.7183 4.4817
2.7183 4.4817 7.3891

Total area under the curve =3.076274>>


D2)Double Intigration By Simpson (1/3)Rd Rule

MATLAB PROGRAM
f=inline('x*x+y*y+5');
x0=input('Enter value of lower limit of first integration = ');
xn=input('Enter value of upper limit of first integration = ');
y0=input('Enter value of lower limit of second integration = ');
ym=input('Enter value of upper limit of second integration = ');
n=input('Enter the number of strips for x = ');
m=input('Enter the number of strips for y = ');
h=(xn-x0)/n;
k=(ym-y0)/m;
temp=x0;
for i=1:m+1
x0=temp;
for j=1:n+1
a(i,j)=f(x0,y0);
x0=x0+h;
end
y0=y0+k;
end
disp(a);
ans=0;
for i=1:2:(n/2+1)
for j=1:2:(n/2+1)

ans=ans+a(i,j)+a(i,j+2)+a(i+2,j+2)+a(i+2,j)+4*(a(i+1,j)+a(i,j+1)+a(i+1,j+2)
+a(i+2,j+1))+16*a(i+1,j+1);
end
end
area=((h/3)*(k/3))*ans;
fprintf('area =%f',area);

Output

Enter value of lower limit of first integration = 0

Enter value of upper limit of first integration = 2

Enter value of lower limit of second integration = 0

Enter value of upper limit of second integration = 2

Enter the number of strips for x = 2

Enter the number of strips for y = 2

5 6 9

6 7 10

9 10 13

area =30.666667>>
4. Program on Curve Fitting Using Least Squer Method (Validation by suitable solver,
all four compulsory)

A)Straightline

MATLAB PROGRAM

n=input('Enter the number of input = ');


for i=1:n
x(i)=input('Enter the value of x = ');
y(i)=input('Enter the value of y = ');
end
S0=0;
S1=0;
S2=0;
S3=0;
for i=1:n;
S0=S0+x(i);
S1=S1+y(i);
S2=S2+x(i)*y(i);
S3=S3+x(i)*x(i);
end
fprintf('______________________________\n')
fprintf('x y x^2 xy\n');
fprintf('______________________________\n')
for i=1:n
fprintf('%f %f %f\n',x(i),y(i),x(i)^2,y(i)*x(i));
end
fprintf('___________________\n')

d=S0*S0-n*S3;
da=S1*S0-n*S2;
db=S0*S2-S1*S3;
a=da/d;
b=db/d;
fprintf('Ans:-a=%f b=%f',a,b);
fprintf('\n\t\ty=%fx+%f',a,b);

Output

Enter the number of input = 7

Enter the value of x = 1

Enter the value of y = .5

Enter the value of x = 2

Enter the value of y = 2.5

Enter the value of x = 3

Enter the value of y = 2


Enter the value of x = 4

Enter the value of y = 4

Enter the value of x = 5

Enter the value of y = 3.5

Enter the value of x = 6

Enter the value of y = 6

Enter the value of x = 7

Enter the value of y = 5.5

______________________________

x y x^2 xy

______________________________

1.000000 0.500000 1.000000

0.500000 2.000000 2.500000 4.000000

5.000000 3.000000 2.000000 9.000000

6.000000 4.000000 4.000000 16.000000

16.000000 5.000000 3.500000 25.000000

17.500000 6.000000 6.000000 36.000000

36.000000 7.000000 5.500000 49.000000

38.500000 ___________________

Ans:-a=0.839286 b=0.071429

y=0.839286x+0.071429>>
D)Quadratic Equation

MATLAB PROGRAM

n=input('Enter the number of inputs = ');


for i=1:n
x(i)=input('Enter the value of x = ');
y(i)=input('Enter the value of y = ');
end
s0=0;
s1=0;
s2=0;
s3=0;
s4=0;
s5=0;
s6=0;
for i=1:n
s0=s0+x(i);
s1=s1+y(i);
s2=s2+x(i)*y(i);
s3=s3+x(i)*x(i);
s4=s4+x(i)*x(i)*y(i);
s5=s5+x(i)*x(i)*x(i);
s6=s6+x(i)*x(i)*x(i)*x(i);
end
a=[s3 s0 n;
s5 s3 s0;
s6 s5 s3;
]
b=[s1;
s2;
s4;
]
v=linsolve(a,b);
fprintf('Ans:a%f b%f c%f', v(1),v(2),v(3));
fprintf('\n\t\ty=%fx^2+%fx+%f',v(1),v(2),v(3));

Output

Enter the number of inputs = 7

Enter the value of x = -3

Enter the value of y = 12

Enter the value of x = -2

Enter the value of y = 4

Enter the value of x = -1

Enter the value of y = 1

Enter the value of x = 0


Enter the value of y = 2

Enter the value of x = 1

Enter the value of y = 7

Enter the value of x = 2

Enter the value of y = 15

Enter the value of x = 3

Enter the value of y = 30

a = 28 0 7

0 28 0

196 0 28

b = 71

82

462

Ans:a2.119048 b2.928571 c1.666667

y=2.119048x^2+2.928571x+1.666667>>
B)Power Equation

MATLAB PROGRAM

n=input('Enter the number of elements = ');


for i=1:n
x(i)=input('Enter the value of x = ');
temp=input('Enter the value of y = ');
y(i)=log(temp);
end
s0=0;
s1=0;
s2=0;
s3=0;
for i=1:n
s0=s0+x(i);
s1=s1+y(i);
s2=s2+x(i)*y(i);
s3=s3+x(i)*x(i);
end
d=s0*s0-n*s3;
da=s1*s0-n*s2;
db=s0*s2-s1*s3;
a1=da/d;
b1=db/d;
b=exp(a1);
a=exp(b1);
fprintf('\n y=(%f)(%f)^x',a,b);

Output

Enter the number of elements = 5

Enter the value of x = 2.1

Enter the value of y = 5.14

Enter the value of x = 2.5

Enter the value of y = 6.788

Enter the value of x = 3.1

Enter the value of y = 10.29

Enter the value of x = 3.5

Enter the value of y = 13.58

Enter the value of x = 4.1

Enter the value of y = 20.578

y=(1.198439)(2.000778)^x>>
C)Exponetial Equation

MATLAB PROGRAM

n=input('Enter the number of elements = ');


for i=1:n
x(i)=input('Enter the value of x = ');
temp=input('Enter the value of y = ');
y(i)=log(temp);
end
s0=0;
s1=0;
s2=0;
s3=0;
for i=1:n
s0=s0+x(i);
s1=s1+y(i);
s2=s2+x(i)*y(i);
s3=s3+x(i)*x(i);
end
d=s0*s0-n*s3;
da=s1*s0-n*s2;
db=s0*s2-s1*s3;
a1=da/d;
b1=db/d;
b=a1;
a=exp(b1);
fprintf('\n y=(%f)e^(%f)x',a,b);

Output

Enter the number of elements = 4

Enter the value of x = 0.1

Enter the value of y = 1.832

Enter the value of x = 0.2

Enter the value of y = 2.238

Enter the value of x = 0.3

Enter the value of y = 2.7333

Enter the value of x = 0.4

Enter the value of y = 3.338

y=(1.500073)e^(1.999818)x>>
5. Program on Interpolation (Validation by suitable solver, all four compulsory)

A)Lagrange’s Interpolation

MATLAB PROGRAM

n=input('\n Enter the number of elements=');


xg=input('\n Enter the value of x=');
for i=1:n
x(i)=input('\n Enter the value of x=');
y(i)=input('\n Enter the value of y=');
end
yg=0;
for i=1:n
nu=1;
de=1;
for j=1:n
if(i~=j)
nu=nu*(xg-x(j));
de=de*(x(i)-x(j));
end
end
L(i)=nu/de;
yg=yg+L(i)*y(i);
end
fprintf('\n yg=%f',yg);

Output

Enter the number of elements=5

Enter the value of x=9

Enter the value of x=5

Enter the value of y=150

Enter the value of x=7

Enter the value of y=392

Enter the value of x=11

Enter the value of y=1452

Enter the value of x=13

Enter the value of y=2366

Enter the value of x=17

Enter the value of y=5202

yg=810.000000>>
B)Newton Forward Difference Interpolation

MATLAB PROGRAM

n=input('\n Enter the number of elements=');


xg=input('\n Enter the value of xg=');
for i=1:n
x(i)=input('\n Enter the value of x=');
y(i,1)=input('\n Enter the value of y=');
end
h=x(2)-x(1);
for j=2:n
for i=1:n-j+1
y(i,j)=y(i+1,j-1)-y(i,j-1);
end
end
fprintf('\n Table=');
for i=1:n
fprintf('\n');
for j=2:(n-i+1)
fprintf('%f',y(i,j));
end
end
u=(xg-x(1))/h;
yg=y(1,1)+u*y(1,2);
p=u*(u-1);
k=2;
for j=3:n
fact=factorial(k);
yg=yg+p*y(1,j)/fact;
p=p*(u-k);
k=k+1;
end
fprintf('\n Ans=%f',yg);
Output

Enter the number of elements=5

Enter the value of xg=46

Enter the value of x=45

Enter the value of y=2.871

Enter the value of x=50

Enter the value of y=2.404

Enter the value of x=55

Enter the value of y=2.083

Enter the value of x=60

Enter the value of y=1.862

Enter the value of x=65

Enter the value of y=1.712

Table=

-0.4670000.146000-0.0460000.017000

-0.3210000.100000-0.029000

-0.2210000.071000

-0.150000

Ans=2.763141>>
C)Inverse Interpolation

MATLAB PROGRAM

n=input('\n Enter the number of elements=');


yg=input('\n Enter the value of yg=');
for i=1:n
x(i)=input('\n Enter the value of x=');
y(i)=input('\n Enter the value of y=');
end
xg=0;
for i=1:n
nu=1;
de=1;
for j=1:n
if(i~=j)
nu=nu*(yg-y(j));
de=de*(y(i)-y(j));
end
end
L(i)=nu/de;
xg=xg+L(i)*x(i);
end
fprintf('\n xg=%f',xg);

Output

Enter the number of elements=4

Enter the value of yg=2

Enter the value of x=0

Enter the value of y=0

Enter the value of x=1

Enter the value of y=1

Enter the value of x=2

Enter the value of y=7

Enter the value of x=3

Enter the value of y=25

xg=1.716138>>
6. Program on ODE(Validation by suitable solver, all three compulsory)
A)Euler’s Method

MATLAB PROGRAM

f=inline('(x*x+y)');
x0=input('Enter the given value of x0= ');
y0=input('Enter the given value of y0= ');
xg=input('Enter the value of xg= ');
acc=input('Enter the desired accuracy= ');
n=2;
h=(xg-x0)/n;
for i=1:n
y1=y0+h*f(x0,y0);
y11=y0+(h/2)*(f(x0,y0)+f((x0+h),y1));
while(abs(y11-y1)>acc)
y1=y11;
y11=y0+(h/2)*(f(x0,y0)+f((x0+h),y1));
end
x0=x0+h;
y0=y11;
end
fprintf('The final value of yg =%f',y11);

Output

Enter the given value of x0= 0

Enter the given value of y0= 1

Enter the value of xg= 0.1

Enter the desired accuracy= 0.0001

The final value of yg =1.105580>> .


B)RUNGE- KUTTA 4th ORDER METHOD

MATLAB PROGRAM

f=inline('((x^2)+(y^2))');
x0=input('\n Enter the value of x0 = ');
y0=input('\n Enter the value of y0 = ');
xg=input('\n Enter the value of xg = ');
h=input('\n Enter the value of step size h = ');
n=(xg-x0)/h;
for i=1:n
k1= h*f(x0,y0);
k2= h*f(x0+(h/2),y0+(k1/2));
k3= h*f(x0+(h/2),y0+(k2/2));
k4= h*f(x0+h,y0+k3);
k=(k1+2*k2+2*k3+k4)/6;
yg=y0+k;
x0=x0+h;
y0=yg;
end
fprintf('\n The final value of yg =%f',yg);

Output

Enter the value of x0 = 0

Enter the value of y0 = 0

Enter the value of xg = 0.4

Enter the value of step size h = 0.2

The final value of yg =0.021360>>


C) SIMULTANEOUS EQUATION RUNGE- KUTTA 4th ORDER METHOD

MATLAB PROGRAM

f=inline('(x+y*z)');
g=inline('(x*x-y*y+0*z)');
x0=input('\n Enter the value of x0= ');
y0=input('\n Enter the value of y0= ');
z0=input('\n Enter the value of z0= ');
xg=input('\n Enter the value of xg= ');
h=input('\n Enter the value of step sirze h = ');
n=(xg-x0)/h;
for i=1:n
k1=h*f(x0,y0,z0);
l1=h*g(x0,y0,z0);
k2=h*f(x0+h,y0+k1,z0+l1);
l2=h*g(x0+h,y0+k1,z0+l1);
k=(k1+k2)/2;
l=(l1+l2)/2;
y0=y0+k;
x0=x0+h;
z0=z0+l;
end
fprintf('\n The final value of yg =%f',y0);
fprintf('\n The final value of zg =%f',z0);

Output

Enter the value of x0= 0

Enter the value of y0= 1

Enter the value of z0= 0.5

Enter the value of xg= 0.2

Enter the value of step sirze h = 0.2

The final value of yg =1.103000

The final value of zg =0.283000>>


7. Program on PDE

MATLAB PROGRAM

f = inline ('(sin(pi*x))');
x0=input('\n Enter the value of x0=');
t0=input('\n Enter the value of t0=');
xn=input('\n Enter the value of xn=');
tn=input('\n Enter the value of tn=');
h=input('\n Enter the value of h=');
k=input('\n Enter the value of k=');
u1=input('\n Enter the value of u1=');
u2=input('\n Enter the value of u2=');
n=(xn-x0)/h;
m=(tn-t0)/k;
for i=1:n+1
x(i)=(x0+h*(i-1));
end
for i=1:m+1
t(i)=(t0+k*(i-1));
end
for i=1:m+1
a(i,1)=u1;
a(i,n+1)=u2;
end
for j=2:n
a(1,j)=f(x0+h*(j-1));
end
v=k/(h*h);
for i=2:m+1
for j=2:n
a(i,j)=v*(a(i-1,j-1))+(1-2*v)*(a(i-1,j))+v*a(i-1,j+1);
end
end
for i=1:m+1
for j=1:n+1
fprintf('\t%2.4f',a(i,j));
end
fprintf('\n\n');
end
Output

Enter the value of x0=0

Enter the value of t0=0

Enter the value of xn=1

Enter the value of tn=0.06

Enter the value of h=0.2

Enter the value of k=0.02

Enter the value of u1=0

Enter the value of u2=0

0.0000 0.5878 0.9511 0.9511 0.5878 0.0000

0.0000 0.4755 0.7694 0.7694 0.4755 0.0000

0.0000 0.3847 0.6225 0.6225 0.3847 0.0000

0.0000 0.3112 0.5036 0.5036 0.3112 0.0000

Das könnte Ihnen auch gefallen