0% found this document useful (0 votes)
27 views

MATLAB Manual Final

This document provides an overview of numerical methods and MATLAB software applications. It discusses installing MATLAB and describes its basic functions, including using MATLAB as a calculator, plotting graphs, generating vectors and matrices, solving linear problems, and performing other numerical computations. Key topics covered include the MATLAB hierarchy of arithmetic operations, plotting multiple functional graphs with axes and legends, using colon operators to generate vectors, and entering and manipulating matrices. The document serves as an introduction and user guide for basic MATLAB operations and capabilities.

Uploaded by

AsadMalik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

MATLAB Manual Final

This document provides an overview of numerical methods and MATLAB software applications. It discusses installing MATLAB and describes its basic functions, including using MATLAB as a calculator, plotting graphs, generating vectors and matrices, solving linear problems, and performing other numerical computations. Key topics covered include the MATLAB hierarchy of arithmetic operations, plotting multiple functional graphs with axes and legends, using colon operators to generate vectors, and entering and manipulating matrices. The document serves as an introduction and user guide for basic MATLAB operations and capabilities.

Uploaded by

AsadMalik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Numerical Methods & Software applications

(MATLAB)

Submitted to:
Mam Aymon Zahra
Submitted by:
Umar Pitafi

Class of 24’
Lab Group: B
Roll # 2K20-CHE-110
Table of Contents
1. Introduction & Installation
2. MATLAB as Calculator & Hierarchy
3. Plotting of graphs
4. Multiple Functional Graphs with axis, legends etc.
5. Vector generation and colon operators
6. Matrix generation and Linear Problem Solving
7. Arrays
8. M-Scripts
9. M-Functions
10. Control Flows ( if……end) loops
11. For…..while loops
12 Polynomials and MATLAB
13 Curve Fitting
14 Interpolation
15 Three Dimensional Plots
1 INTRODUCTION AND INSTALLATION

Introduction:
The name MATLAB stands for Matrix laboratory. MATLAB was written originally to provide
easy access to matrix software developed by the LINPACK (linear system package) and
EISPACK (Eigen system package) projects. MATLAB is a high-performance language for
technical computing. It integrates computation, visualization, and programming environment.
Furthermore, MATLAB is a modern programming language environment: it has sophisticated
data structures, contains built-in editing and debugging tools, and supports object-oriented
programming. These factors make MATLAB an excellent tool for teaching and research.
MATLAB has many advantages compared to conventional computer languages (e.g., C,
FORTRAN) for solving technical problems. MATLAB is an interactive system whose basic data
element is an array that does not require dimensioning.

Installation:
The Installation process is remarkably simple for MATLAB as described in the following steps
1. Go to http://www.mathworks.com/downloads/web_downloads/
2. Sign into your MATLAB account

3. After signing in a page will appear with the download link click on the download button
and download the software

Page | 1
4. After downloading , Open the installer and let it unpack

5. After unpacking the Installer will open, Accept the terms and conditions to continue
installation process and click on next

6. Confirm and Select your License

Page | 2
7. Select your Installation destination

8. Under Products section select MATLAB and move to Confirmation on Confirmation Tab
click on Begin Installation

9. The necessary files for MATLAB will now be downloaded and installed

Page | 3
10. After installation, the following screen will appear

Page | 4
2 MATLAB AS A CALCULATOR AND HIERARCHY OF ARITHMETIC
OPERATIONS

2.1. MATLAB as a Calculator


As an example of a simple interactive calculation, just type the expression you want to
evaluate. Let us start at the very beginning. For example, let us suppose you want to calculate
the expression, 5+17 x10.

You type it at the prompt command (>>) as follows,

The answer generated

Now in the workspace we can see the answer generated by the expression 5+17 x10 is stored
as Ans 175 this is because we have not specified any variable to the expression and
MATLAB uses default variable (Ans) , to avoid this we can assign a variable to our
expression as

Then the answer generated will be stored as a value of variable x

Now this variable can be manipulated in form of function or arguments to generate various
answers
For Instance
Lets suppose we want to calculate Y=42x-194 then by using MATLAB we find this value of
Y by simply writing the argument

Page | 5
The answer generated for the expression will be Stored as variable Y because we have
assigned the expression a variable

2.2. Hierarchy of arithmetic operations


Exponentiations are done first, followed by multiplications and divisions, and finally by
additions and subtractions. However, the standard order of precedence of arithmetic operations
can be changed by inserting parentheses. For example, the result of 5+17x3 is quite different
than the similar expression with parentheses (5+17) x10.The results are 175 and 220,
respectively. Parentheses can always be used to overrule priority, and their use is recommended
in some complex expressions to avoid ambiguity.
Therefore, to make the evaluation of expressions unambiguous, MATLAB has established a
series of rules. The order in which the arithmetic operations are evaluated is given in the table
below

Hierarchy of arithmetic operations in MATLAB

consider another example


81 7
+ 45 𝑥
9 + 222 19
In MATLAB it becomes
81/(9+22^2)+45*(7/19)

Page | 6
If the parenthesis is missing, then the answer varies

So here what we get: two different results. Therefore, we want to emphasize the
importance of precedence rule to avoid ambiguity.

Page | 7
3 PLOTTING OF GRAPHS

MATLAB has an excellent set of graphic tools. Plotting a given data set or the result of
computation is possible with very few commands. You are highly encouraged to plot
mathematical functions and results of analysis as often as possible. Trying to understand
mathematical equations with graphics is an enjoyable and very efficient way of learning math.
Being able to plot mathematical functions and data freely is the most key step, and this section is
written to assist you to do just that.
The MATLAB command to plot a graph is plot(x,y).
The vectors x = [5 10 15 20 ] and y = [2 10 11 19 ]
The MATLAB Command for Plotting 2d graphs is as follows

Which produces the following graph

The plot functions has different forms depending on the input arguments. If y is a vector plot(y)
produces a piecewise linear graph of the elements of y versus the index of the elements of y. If
we specify two vectors, as mentioned above, plot(x,y) produces a graph of y versus x.

Page | 8
For example, to plot the function sin (x) on the interval [0,5pi], we must create a vector of x
values ranging from 0 to 5pi then compute the cos of these values, and finally plot the graph
It can be seen in the screenshot attached below that first we created an interval of 0-5pi and
named it X and after that we assigned a function to that interval and finally gave the plot
command to plot the graph between interval and its functional values

Page | 9
4 MULTIPLE FUNCTIONAL GRAPHS WITH AXIS, LEGENDS

Multiple (x; y) pairs arguments create multiple graphs with a single call to plot. For example,
these statements plot three related functions of x as described in the previous section say we want
to plot multiple functions on a single interval which is defined already, this can be done in
MATLAB by writing following commands

It can seen in the command window that we created various functions for plotting multiple
graphs and in the plot command we added another command ‘—’ for dashed lined for a plain
curve we assigned ‘-‘ to our function and for dotted curve we assigned ‘:’ to our function
Axis , Legends , Titles , annotations and assigning colors can also be done in MATLAB simply
as shown in commands given in the screenshot on the next page

Page | 10
Page | 11
5 VECTOR GENERATION AND COLON OPERATORS

5.1. The Colon Operator


The colon operator will prove particularly useful and understanding how it works is the key to
efficient and convenient usage of MATLAB. It occurs in several different forms. Often, we must
deal with matrices or vectors that are too large to enter one element at a time. For example,
suppose we want to enter a vector x consisting of points (0.1,0.2,0.3………7)
Then we can generate a vector with the help of colon matrix which will have a step size of 0.1
the command for this goes as follows

x=0:0.1:7 which generates the following results in MATLAB

The total elements/points produced will be seventy-one

Matrices are the basic elements of the MATLAB environment. A matrix is two-dimensional
array consisting of m rows and n columns. Unusual cases are column vectors (n = 1) and row
vectors (m = 1).

5.2. Matrix generation

Matrices are fundamental to MATLAB. Therefore, we need to become familiar with matrix
generation and manipulation. Matrices can be generated in several ways.

5.2.1 Entering a vector

A vector is a special case of a matrix. The purpose of this section is to show how to create
vectors and matrices in MATLAB. The elements of vectors in MATLAB are enclosed by square
brackets and are separated by spaces or by commas for example this command can be used to
generate a vector I

I = [ 1 2 3 4 5 6 7 8 9 10 11 12 13] as seen in the screenshot on the next page

Page | 12
Column vectors are created in an equivalent way, however, semicolon (;) must separate the
components of a column vector as seen in the screenshot below

On the other hand, a row vector is converted to a column vector using the transpose operator.
The transpose operation is denoted by an apostrophe or a single quote ‘ a screenshot is attached
below showing the working of this command

Furthermore, to access blocks of elements, we use MATLAB's colon notation (:). For example, to access
the first three elements of I, we write,

Then MATLAB shows us

Page | 13
Or, all elements from the third through the last elements

Page | 14
6 MATRIX GENERATION AND LINEAR PROBLEM SOLVING

6.1 Entering a matrix in MATLAB

A matrix is an array of numbers. To type a matrix into MATLAB you must


1. begin with a square bracket, [
2. separate elements in a row with spaces or commas (,)
3. use a semicolon (;) to separate rows
4. end the matrix with another square bracket, ]

Here is a typical example. To enter a matrix A, such as,

1 2 4
[1 1 2 ]
6 2 31
Type

Then the result generated is shown below

Note that the use of semicolons (;) here is different from their use mentioned earlier to
suppress output or to write multiple commands in a single line. Once we have entered the matrix,
it is automatically stored and remembered in the Workspace. We can refer to it simply as matrix
A. We can then view a particular element in a matrix by specifying its location. We write,
>>A(2,1)
Shown in the screenshot attached below

Page | 15
Linear Spacing
On the other hand, there is a command to generate linearly spaced vectors: linspace. It
is similar to the colon operator (:) but gives direct control over the number of points.
For example,

y = linspace(a,b)

generates a row vector y of one hundred points linearly spaced between and including a and b.
y = linspace(a,b,n)

generates a row vector y of n points linearly spaced between and including a and b. This is
useful when we want to divide an interval into a number of subintervals of the same length.
For example,

Another example

6.2 Colon operator in a matrix


The colon operator can also be used to pick out a certain row or column. For example, the
statement A (m:n,k:l specifies rows m to n and column k to l. Subscript expressions refer to
portions of a matrix. For example,

>>A(2,:)

Will generate an answer

Ans = 1 1 2

As show in the screenshot attached below

Page | 16
The colon operator can also be used to extract a sub-matrix from a matrix A.

>>A(:,2:3)

6.2.2 Creating a submatrix


To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the matrix A,
do the following

To interchange rows 1 and 2 of A, use the vector of row indices together with the colon operator.

It is important to note that the colon operator (:) stands for all columns or all rows. To
create a vector version of matrix A, do the following

Page | 17
6.2.3 Deleting row or column

To delete a row or column of a matrix, use the empty vector operator, [ ].


>>A(3,:) = []

Third row of matrix A is now deleted.

Page | 18
7 ARRAYS

MATLAB has two distinct types of arithmetic operations: matrix arithmetic operations
and array arithmetic operations. We have seen matrix arithmetic operations in the previously

7.1 Matrix arithmetic operations


As we mentioned earlier, MATLAB allows arithmetic operations: +, -, *, and ^ to be
conducted on matrices.

7.2 Array arithmetic operations


On the other hand, array arithmetic operations or array operations for short, are done element-by-element.
The period character, ., distinguishes the array operations from the matrix operations. However, since the
matrix and array operations are the same for addition (+) and subtraction (-), the character pairs (.+) and
(.-) are not used. The list of array operators is shown below in Table below If A and B are two matrices of
the same size with

If we have

Then >> C = A.*B produces another matrix C of the same size with elements cij = aijbij . For
example, using the same 3 by 3 matrices, shown on next page

Page | 19
To raise a scalar to a power, we use for example the command 10^2. If we want the operation to be
applied to each element of a matrix, we use .^2. For example, if we want to produce a new matrix whose
elements are the square of the elements of the matrix A, we enter
>> A.^2

The relations below summarize the above operations. To simplify, let's consider two vectors U
and V with elements U = [ui] and V = [vj ].

The summary of matrix and operations is given in a table below

Page | 20
8 M- FILE SCRIPTS

8.1 Introduction
So far in these labs discussed in this manual , all the commands were executed in the Command
Window. The problem is that the commands entered in the Command Window cannot be saved
and executed again for several times. Therefore, a different way of executing repeatedly
commands with MATLAB is:
1. to create a file with a list of commands,
2. save the, and
3. run the file
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

8.2 M-File Scripts


A script file is an external file that contains a sequence of MATLAB statements. Script
¯les have a filename extension .m and are often called M-¯les. M-¯les 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.

Consider the example for Bisection method in MATLAB with the help of M-file scripts
To performs iterations to achieve some tolerance following script can be written in MATLAB
f = @ (x) x^4-16*x^3+72*x^2-96*x+24;
a= -.05;
b= 7;
n=100;
T=10^-5;
if f(a)*f(b)<0
for i=1:n
C = (a+b)/2;
RE=abs((C-b)/C);
fprintf('C%d=%.4f\n',i,C)
if abs(C-b)/C<T || abs(C-a)/C<T

break
end
if f(a)*f(C)<0
b = C;
else if f(b)*f(C)<0
a = C;
end
end
end
else disp('Bad roots')
end

Page | 21
The results generated from this mfile-script are as follows

The MATLAB editor is both a text editor specialized for creating M-files and a graphical
MATLAB debugger. The MATLAB editor has numerous menus for tasks such as saving,
viewing, and debugging. Because it performs some simple checks and also uses color to
differentiate between various elements of codes, this text editor is recommended as the tool of
choice for writing and editing M-files.

8.2.1 Script side-effects


All variables created in a script ¯le are added to the workspace. This may have undesirable
effects, because:
1. Variables already existing in the workspace may be overwritten.
2. The execution of the script can be affected by the state variables in the workspace.

As a result, because scripts have some undesirable side-effects, it is better to code any
complicated applications using function M-file.

Page | 22
9 M-FILE FUNCTIONS

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

9.1. Anatomy of a M-File function


The first line of a function M-¯le starts with the keyword function. It gives the function
name and order of arguments. In the case of function factorial, there are up to one output
argument and one input argument. Table below summarizes the M-file function.

As an example, for n = 10, the result M-file function is

function f = factorial(n)
n=input ('enter desired number')
f=prod(1:n);

the result generated is attached below

Page | 23
In addition, it is important to note that function name must begin with a letter and must be no
longer than the maximum of 63 characters. Furthermore, the name of the text file that you save
will consist of the function name with the extension .m. Thus, the above example file would be
factorial.m.

The difference between M-Script and M-Functions are listed below

9.1.1. Input and output arguments


As mentioned above, the input arguments are listed inside parentheses following the function
name. The output arguments are listed inside the brackets on the left side. They are used to
transfer the output from the function file. The general form looks like this

function [outputs] = function_name(inputs)


Function file can have none, one, or several output arguments.

9.1.2. Input to a script file


When a script file is executed, the variables that are used in the calculations within the file must
have assigned values. The assignment of a value to a variable can be done in three ways.

1. The variable is defined in the script file.


2. The variable is defined in the command prompt.
3. The variable is entered when the script is executed.

We have already seen the two first cases. Here, we will focus our attention on the third one.
In this case, the variable is defined in the script file. When the file is executed, the user is
prompted to assign a value to the variable in the command prompt. This is done by using
the input commands. Same bisection method as discussed previously is mentioned as an example
on the next page but with changes for the input

Page | 24
f = input(' desired function =');
a= input('Enter domain point a =');
b= input ('domain point b=');
n=input ('desired iterations to be performed=');
T= input ('enter desired tolerance to be achieved=');
if f(a)*f(b)<0
for i=1:n
c = (a+b)/2;
RE=abs((c-b)/c);
fprintf('c%d=%.4f\n',i,c)
if abs(c-b)/c<T || abs(c-a)/c<T

break
end
if f(a)*f(c)<0
b = c;
else if f(b)*f(c)<0
a = c;
end
end
end
else disp('Bad roots')
end

9.1.3. Output commands

As discussed before, MATLAB automatically generates a display when commands are executed.
In addition to this automatic display, MATLAB has several commands that can be used to
generate displays or outputs.
Two commands that are frequently used to generate output are: disp and fprintf. The main
differences between these two commands can be summarized as follows

Page | 25
10 CONTROL FLOWS ( IF……END) LOOPS

10.1. Introduction
MATLAB is also a programming language. Like other computer programming languages,
MATLAB has some decision making structures for control of command execution. This decision
making or control flow structures include for loops, while loops, and if-else-end constructions.
Control flow structures are often used in script M-¯les and function M-files. By creating a file
with the extension .m, we can easily write and run programs. We do not need to compile the
program since MATLAB is an interpretative (not compiled) language. MATLAB has thousands
of functions, and you can add your own using m-files. MATLAB provides several tools that can
be used to control the flow of a program (script or function). In a simple program as shown in the
previous Chapter, the commands are executed one after the other. Here we introduce the flow
control structure that make possible to skip commands or to execute specific group of
commands.

10.2. Control flow

MATLAB has four control flow structures: the if statement, the for loop, the while loop,
and the switch statement.

The ``if...end'' structure


MATLAB supports the variants of if construct.
if ... end
if ... else ... end
if ... elseif ... else ... end

The simplest form of the if statement is

if expression
statements
end

Here is an example

Input

Page | 26
Output

It should be noted that:


1. elseif has no space between else and if (one word)
2. no semicolon (;) is needed at the end of lines containing if, else, end
3. indentation of if block is not required but facilitate the reading.
4. the end statement is required

Page | 27
11 FOR…..WHILE LOOPS

The ``for...end'' loop


In the for ... end loop, the execution of a command is repeated at a fixed and predetermined
number of times. The syntax is

for variable = expression


statements
end

Usually, expression is a vector of the form i:s:j. A simple example of for loop is

It is a promising idea to indent the loops for readability, especially when they are nested. Note
that MATLAB editor does it automatically.
Multiple for loops can be nested, in which case indentation helps to improve the
readability.

The ``while...end'' loop


This loop is used when the number of passes is not specified. The looping continues until a
stated condition is satisfied. The while loop has the form:

while expression
statements
end

The statements are executed as long as expression is true.

Page | 28
x=1
while x <= 10
x = 3*x
end
It is important to note that if the condition inside the looping is not well defined, the looping
will continue indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.

The for while and for end examples were previously discussed for the bisection method in this
section I have attached a m script with the control flows for Newton Raphson method
f = @(x) x^3 - 4*x -5;
df = @(x) 3*(x^2) -4;
x0 = 2;
e = 0.000001;
n = 10;
if df(x0)~=0
for i=1:n
x1 = x0 - f(x0)/df(x0);
fprintf('x%d = %.16f\n',i,x1)
if abs(x1-x0)/x1<e
break
end
x0 = x1;
end
else
disp('newton method cannot run because derivative of given function is
zero');
end

Which gives following results

Page | 29
12 POLYNOMIALS AND MATLAB

12.1 Introduction
Polynomials are mathematical expressions that are frequently used for problem solving and
modeling in science and engineering. In many cases an equation that is written in the process of
solving a problem is a polynomial, and the solution of the problem is the zero of the
polynomials. MATLAB has a wide selection of functions that are specifically designed for
handling polynomials.

Polynomials are functions that have the form


f(x) = ax"+an-x-1 +………..a1x+ao
In MATLAB polynomials are represented by a row vector in which the first element are
coefficients an an-1………….a1,a0, The first element is the coefficient of the x with highest
power. The vector has to include all the coefficients, including the one that are equal to 0 for
example

12.2 Value of a Polynomial


The value of a polynomial can be calculated with the function polyval that has the form
Polyval(p,x)

Where P is a vector with coefficients of Polynomial and X is a number or a variable that has an
assigned value or a computable expression
X can also be a vector or a matrix . In such cases the polynomial is calculated for each element
and the answer is a vector or a matrix
For instance
A polynomial x^5 - 12.1*x^4 + 40.59*x^3 - 17.015*x^2 – 71.95*x + 35.88
This problem can be solved in command window with the commands shown on the next page

Page | 30
For x = 9

12.3. Roots of a polynomial


Roots of a polynomial are the values of the argument for which the value of the polynomial is
equal to zero, for instance the roots of the polynomial
F(X) = x^3 – 2x – 3 are the values for which x^2 – 2x - 3 = 0 which are x=-1 and x=3
MATLAB has a function called roots , which determines the root or roots of a polynomial the
form of the function is

r= roots(p)
where r is a column vector with the roots of a polynomial and p is the row vector with the
coefficients of the polynomial

Page | 31
When roots of the polynomial are known the poly command can be used for determining the
coefficients of the polynomial, the command poly is

P=poly( r )

12.4. Addition Multiplication and division of Polynomials

12.4.1. Addition
Two polynomials can be added (or subtracted) by adding the vectors of the coefficients. If the
polynomials are not of the same order (which means that the vectors of the coefficients are not of
the same length), the shorter vector has to be modified to be of the same length as the longer
vector by adding zeros (called padding)
As shown in MATLAB let p1 be the first polynomial and p2 be the second of same dimensions

Page | 32
Then

12.4.2. Multiplication
Two polynomials can be multiplied with the MATLAB built in function conv which has the
form
C = conv (a,b)
Where c is a vector of the coefficients of the polynomial that is the product of multiplication and
a,b are the vectors if the polynomials that are being multiplied
The two polynomials do not have the same order

Page | 33
Multiplication of three or more polynomials us done by using the conv function repeatedly

For example

12.4.3. Division
A polynomial can be divided by another polynomial with the Matlab builtin function deconv
which has the following form
[q,r] = deconv(u,v)
Where q is a vector with the coefficients of the quotient polynomial, r is a vector with the
coefficients of the remainder polynomial and u is the vector with the numerator polynomial and
v is a vector with the coefficients of the denominator polynomial

For example

Page | 34
13 CURVE FITTING

13.1. Introduction
Curve fitting, also called regression analysis, is a process of fitting a function to a set of data
points. The function can then be used as a mathematical model of the data. Since there are many
types of functions (linear, polynomial, power, expo- nential, etc.) curve fitting can be a
complicated process. Many times there is some idea of the type of function that might fit the
given data and the need is only to determine the coefficients of the function. In other situations,
where nothing is known about the data, it is possible to make different types of plots which
provide information about possible forms of functions that might give a good fit to the data. This
section describes some of the basic techniques for curve fitting, and the tools that MATLAB has
for this purpose.

13.2. Curve fitting with the polyfit function


Polynomials can be used to fit data points in two ways. In one, the polynomial passes through all
the data points, and in the other the polynomial does not necessarily pass through any of the
points, but overall gives a good approximation of the data. The two options are described below.
Polynomials that pass through all the points
When n points (x, y) are given, it is possible to write a polynomial of degree n-1 that pass
through all the points. For example, if two points are given it is possible to write a linear
equation in the form of y mx+b that passes through the points. With three points the equation has
the form of y ax2 + bx + c. With n points the polynomial has the form: a,x−1 +a_2x²+...+ax+ao.
The coefficients of the polynomial are determined by substituting each point in the polynomial,
and then solving the n equations for the coefficients. As will be shown later in this section,
polynomials of high degree might give a large error if they are used to esti- mate values between
data points.
Polynomials that do not necessarily pass through all the points
When n points are given, it is possible to write a polynomial of degree less than n-1 that does not
necessarily pass through any of the points, but overall approximates the data. The most common
method of finding the best fit to data points is the method of least squares. In this method the
coefficients of the polynomial are determined by minimizing the sum of the squares of the
residuals at all the data points. The residual at each point is defined as the difference between the
value of the polynomial and the value of the data.

Page | 35
Curve fitting with polynomials is done in MATLAB with the polyfit function, which uses the
least squares method. The basic form of the polyfit function is
p = polyfit (x,y,n)
where p is the vector of the coefficient of the polynomial that fits the data and x is a vector with
horizontal coordinate of the data points and y is a vector with vertical coordinate of the data
points and n is the degree of polynomial

Page | 36
14 INTERPOLATION

14.1. Introduction
Interpolation is estimation of values between data points. MATLAB has interpolation functions
that are based on polynomials, which are described in this section, and on Fourier
transformation, which are outside the scope of this book. In one- dimensional interpolation each
point has one independent variable (x) and one dependent variable (y). In two-dimensional
interpolation each point has two independent variables (x and y) and one dependent variable (z).

14.2 One dimensional interpolation


If only two data points exist, the points can be connected with straight, and a linear equation
(polynomial of first order) can be used estimate values between the points. As was discussed in
the previous section, three four) data points exist, a second (or third) order polynomial can be
determined pass through the points and then be used to estimate values between the points. the
number of points increases a higher order polynomial is required for the polynomial pass through
all the points. Such a polynomial, however, will not necessarily give good approximation of the
values between the points.
In linear interpolation line between two data points has constant slope, and there a change the
slope at every point. A smoother interpolation curve can be obtained using quadratic, cubic
polynomials. these methods, called quadratic splines cubic splines, second, third order
polynomial' used to interpolate between two points. The coefficients polynomial are determined
using from additional that are adjacent the two data points. The theoretical background the
determination constants the polynomials beyond scope of this book and can found books on
numerical analysis.
One-dimensional interpolation in MATLAB is done with the interpl (last character is the number
one) function, which has the form:
yi = interp1(x,y,xi, 'method')
where yi is the interpolated value and x is a vector with horizontal coordinate of input data points
and y Is a vector with vertical coordinate of the input data points xi is the horizontal coordinate
of the interpolation point and ‘method’ is method of interpolation typed as a string its optional

Page | 37
Which generates

Page | 38
15 THREE DIMENSIONAL PLOTS

15.1 Introduction
Three-dimensional (3-D) plots can be a useful way to present data that consists of more than two
variables. MATLAB provides various options for displaying three- dimensional data. They
include line and wire, surface, mesh plots, and many oth- ers. The plots can also be formatted to
have a specific appearance and special effects. Many of the three-dimensional plotting features
are described in this chap- ter. Additional information can be found in the Help Window under
Plotting and Data Visualization.

15.2. Line plots


A three-dimensional line plot is a line that is obtained by connecting points in a three-
dimensional space. A basic 3-D plot is created with the plot3 command, which is very similar to
the plot command, and has the form:

plot3 (x, y, z, 'line specifiers', 'PropertyName', property value)


here x y and z are the vectors of the coordinates of the points and remaining data written in
single quotations are optional

1. The three vectors with the coordinates of the data points must have the same number
of elements.
2. The line specifiers, properties, and property values are the same as in 2-D plots

For example
if the coordinates x, y, and z are given as a function of the parameter r by
x = sqrt(tsint(st))
y= sqrt(tcos(2t))
z= 0.5t

Page | 39
A plot of the points for 0≤t≤6pi can be produced by the following script file:

15.3 Mesh and surface plots


A mesh or a surface plot is created with the mesh or surf commands, which have the forms:
mesh(X,Y,Z) surf(X,Y,Z)
where X, Y, are matrices with the coordinates of the grid and Z is a matrix with the value of z at
the grid points. The mesh plot is made of lines that connect the points.
In the surface plot, areas within the mesh lines are colored. As an example, the following script
file contains a complete program that creates the grid and then makes a mesh (or surface) plot of
the function
Z = (xy^2)/x^2+y^2 over the domain -1 ≤x≤3 and 1 sy≤4.
Shown on next page

Page | 40
Page | 41
CONTENTS
1 Introduction and Installation ................................................................................................................ 1
2 MATLAB as a Calculator and Hierarchy of arithmetic operations ........................................................ 5
3 Plotting of graphs .................................................................................................................................. 8
4 Multiple Functional Graphs with axis, legends................................................................................... 10
5 Vector Generation and Colon operators............................................................................................. 12
6 Matrix generation and Linear Problem Solving .................................................................................. 15
7 Arrays.................................................................................................................................................. 19
8 M- File Scripts .................................................................................................................................... 21
9 M-File Functions ................................................................................................................................. 23
10 Control Flows ( if……end) loops ................................................................................................... 26
11 For…..while loops .......................................................................................................................... 28
12 Polynomials and MATLAB ............................................................................................................... 30
13 Curve Fitting .................................................................................................................................... 35
14 Interpolation ................................................................................................................................... 37
15 Three Dimensional Plots ................................................................................................................. 39

You might also like