Professional Documents
Culture Documents
ES106 Manual - 2022-23
ES106 Manual - 2022-23
ES106 Manual - 2022-23
VALLABHVIDYANAGAR
ES106
Programming For Engineers
Lab Manual
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
VISION:-
"Produce globally employable innovative engineers with core
values”
MISSION:-
INDEX
Ex. Page
Date Title Marks Faculty Sign
No. No.
1. Introduction to MATLAB
2. Arithmetic Expressions
5. Logical Branching
6. Loops
7. Functions
8. 2D Plot
9 3D Plot
13. Interpolation
Introduction to MATLAB
Experiment No: 1
Date:
Theory:
MATLAB
MATLAB stands for matrix laboratory is a very powerful technical language for mathematical
programming. After logging into your account, you can enter MATLAB by double-clicking on
the MATLAB shortcut icon on your Windows desktop. When you start MATLAB, a special
window called the MATLAB desktop appears. The desktop is a window that contains other
windows. The major tools within or accessible from the desktop are:
As an example of a simple interactive calculation, just type the expression you want to evaluate.
Let's start at the very beginning. For example, let's suppose you want to calculate the
expression, 1 + 2 * 3. You type it at the prompt command (>>) as follows,
>> 1 + 2 ∗ 3
ans =
7
You will have noticed that if you do not specify an output variable, MATLAB uses a default
variable ans, short for answer, to store the results of the current calculation. Note that the
variable ans is created (or overwritten, if it is already existed). To avoid this, you may assign a
value to a variable or output argument name. For example,
>> 𝑥 = 1 + 2 ∗ 3
x =
7
will result in x being given the value 1 + 2*3 = 7. This variable name can always be used to
refer to the results of the previous computations. Therefore, computing 4x will result in
>> 4 ∗ 𝑥
ans =
28.0000
Before we conclude this minimum session, Table gives the partial list of arithmetic operators.
MATLAB variables are created with an assignment statement. The syntax of variable
assignment is
variable name = a value (or an expression)
For example,
>> 𝑥 = 𝑒𝑥𝑝𝑟𝑒𝑠𝑠𝑖𝑜𝑛
manual entry
built-in functions
user-defined functions
>> clear
The command clear or clear all removes all variables from the workspace. This frees up system
memory. In order to display a list of the variables currently in the memory,
type
>> who
while, whos will give more details which include size, space allocation, and class of the
variables.
To view the online documentation, select MATLAB Help from Help menu or MATLAB Help
directly in the Command Window. The preferred method is to use the Help Browser. The Help
Browser can be started by selecting the ? icon from the desktop toolbar. On the other hand,
information about any command is available by typing
MATLAB offers many predefined mathematical functions for technical computing which
contains a large set of mathematical functions. Typing help fun and help spec fun calls up full
lists of elementary and special functions respectively. There is a long list of mathematical
functions that are built into MATLAB. These functions are called built-ins. Many standard
mathematical functions, such as sin(x), cos(x), tan(x), ex, ln(x), are evaluated by the functions
sin, cos, tan, exp, and log respectively in MATLAB.
Handling array:-
Descriptio
Command Output (Results)
n
Row array A=
A = [11,12,13,14]
11 12 13 14
Column A=
array 11
A = [11;12;13;14]
12
13
14
Matrix A =
A = 11 12 13 14
[11:14;21:24;31:34;41:44 21 22 23 24
] 31 32 33 34
41 42 43 44
Calculate
Y = sin(x)
sin(.) of
the x-
array
Plot the
Plot(Y)
y-array
Exercise
1 Get familiarised with MATLAB window, MATLAB Script, Console.
2 Perform basic codes given in the manual and check how you can work with
MATLAB.
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Arithmetic Expressions
Experiment No: 2
Date:
Theory:
Arithmetic expressions
𝑐 = 𝑎 + 𝑏
𝑑 = 𝑎 − 𝑏
𝑒 = 𝑎 ∗ 𝑏
𝑓 = 𝑎/𝑏
𝑔 = 𝑎\𝑏
𝑥 = 7;
𝑦 = 3;
𝑧 = 𝑥^𝑦
Exercises:
1 Write a script that reads two nos. from key board and gives their addition,
subtraction, multiplication, division.
2 Write a Script to find area of circle and rectangle.
3 Write a script to convert Celsius to Fahrenheit.
4 Write a script to convert days into months and days.
5 Write a script to convert hours into minutes and seconds.
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Objective: To learn to initialize vectors and matrices and use of arithmetic operators for them.
Theory:
Matrices :
An array 𝐴 of 𝑚 rows and 𝑛 columns is called a matrix of order (𝑚 × 𝑛), which consists of a
total of 𝑚𝑛 elements arranged in the following rectangular array:
𝑎11 𝑎12 ⋯ 𝑎1𝑛
𝑎21 𝑎22 ⋯ 𝑎2𝑛
𝐴=[ ⋮ ⋮ ⋱ ⋮ ] → (𝑚 × 𝑛)
𝑎𝑚1 𝑎𝑚2 ⋯ 𝑎𝑚𝑛
The elements of the matrix are denoted 𝑎𝑖𝑗 , where 𝑖 indicates the row number and 𝑗 the column
number. In MATLAB, the order of the matrix is referred to as its size.
When 𝑎𝑖𝑗 = 𝑎𝑖1 , that is, there is only one column, then is called a column matrix or, more
commonly, a vector, that is,
𝑎11 𝑎1
𝑎21 𝑎2
𝑎 = [ ⋮ ] = [ ⋮ ] → (𝑚 × 1)
𝑎𝑚1 𝑎𝑚
When 𝑎𝑖𝑗 = 𝑎1𝑗 , that is, there is only one row, then is called a row matrix or a vector,
that is,
This is the default definition of a vector in MATLAB. In this case, 𝑛 is the length of the vector.
Thus, vector can be represented by a row or a column matrix.
Creation of vector
Colon Notation
𝑥 = 𝑠: 𝑑: 𝑓 𝑜𝑟 𝑥 = (𝑥: 𝑑: 𝑓) 𝑜𝑟 𝑥 = [𝑠: 𝑑: 𝑓]
where, 𝑠 = start or initial value, 𝑑 = increment or decrement, 𝑓 = end or final value. If 𝑑 is not
specified then value 1 is considered as increment. With any of these command, the following
row vector 𝑥 is created.
where, 𝑠 + 𝑛𝑑 ≤ 𝑓. Note that the number of values 𝑛 created for 𝑥 is not specified directly.
Linespace
In the second method, one specifies 𝑛 equally spaced values starting at 𝑠 and ending at 𝑓 as
follow:
𝑥 = 𝑙𝑖𝑛𝑠𝑝𝑎𝑐𝑒(𝑠, 𝑓, 𝑛)
Creation of Matrix
This matrix can be created several ways, the basic syntax to create a matric is
𝐴 = [𝑎11 𝑎12 𝑎13 ; 𝑎21 𝑎22 𝑎23 ; 𝑎31 𝑎32 𝑎33 ; 𝑎41 𝑎42 𝑎43 ]
where the semicolons are used to indicate the end of a row. Each row must have the same
number of columns. If a more readable presentation is desired, then one can use the form
A fourth way is to create four separate row vectors, each with the same number of columns,
and then combine these vectors to form the matrix. In this case, we have
𝐴 = [𝑣1 ; 𝑣2 ; 𝑣3 ; 𝑣4 ]
where the semicolons in the first four lines are used to suppress display to the command
window. The fourth form is infrequently used.
Multiplication
and is of order (𝑚 × 𝑛). Notice that the product of two matrices is defined only when the
adjacent integers of their respective orders are equal; 𝑘 in this case. In other words,
(𝑚 × 𝑘)(𝑘 × 𝑛), where the notation indicates that we have summed terms as indicated in Eq.
The MATLAB expression for matrix multiplication is
𝐶 =𝐴∗𝐵
The following table lists out few important functions used in MATALAB.
Exercises:
1. Write a script to determine sin(x) at ten equally spaced values from -𝜋 ≤ 𝑥 ≥ 𝜋.
2. Write a script to construct the following matrix:
3 5 7 9 11
𝐴 = [20.0 20.25 20.5 20.75 21.0] → (3 × 5)
1 1 1 1 1
a. Find the element in the first row and first column
b. the element in the third row and fourth column.
c. All the elements in the second column.
d. All the elements in the second row.
e. submatrix composed of the elements in columns 3 to 5 and rows 1 to 3.
f. create a matrix that is of the same size as , but with all of its elements equal to 4.
3. Write a script to generate the following special matrix:
0 1 1 0 2 2 0 3 3
|1 0 1| |2 0 2| |3 0 3|
1 1 0 2 2 0 3 3 0
0 4 4 0 5 5 0 6 6
|4 0 4| |5 0 5| |6 0 6|
4 4 0 5 5 0 6 6 0
0 7 7 0 8 8 0 9 9
|7 0 7| |8 0 8| |9 0 9|
[7 7 0 8 8 0 9 9 0]
4. Write script for vector exponential using dot (.) operation for x= 2 and y=2k where k is
from 2 to 8
5. Write a script to solve the following system of equations:
Objective: To learn the basic concept of how data is imported and to get formatted output.
Theory:
Arrays of data can be solicited by a script or function and then entered by the user by
employing input. In addition, input can display to the MATLAB command window a
message instructing the user what is to be entered.
However, the actual form of the data depends on whether the data represent a scalar,
vector, or matrix and whether these quantities are numbers or strings
To input a single numerical quantity (scalar),
n=input(‘Enter Value of n’)
x = input(‘prompt’) Age=input(‘Enter Your age’)
str Country=input(‘Enter your country’,’s’)
= input(‘prompt’,'s')
Executing this statement, it appears ‘Enter Your age’ in command window and wait
for users to give input scalar value.
To input a single string quantity, we append 's' at the end of the input function. And
to enter vector input, write elements in square brackets. For example x=[1 2 3 4 5 6].
Data files created in Microsoft Excel can be read into MATLAB with the function
[X, Y] = xlsread('Filename')
where X will be an array containing the columns and rows of data and Y will be
a cell array containing any text headers that accompany the data. The file name
must contain the suffix ‘.xls’.
For the output of script file, it can be obtained using various method.
a). If you remove semicolon at the end of statement it will display value of
variable in command window.
b). By using disp command. disp(x)= prints the value of x
disp(‘x’)= prints ‘x’ as string
c). By using fprintf command, one can format the output data based on our
requirements. fprintf(‘Hello World’)= Prints ‘Hello World’ in command
window.
fprints(‘Soni gets %3d marks in maths’,x)= prints the string ‘Soni gets
85 marks in maths.’ Where value of x=85 is predefined.
Format Specifiers:
%s Format as String
%d Format with no fractional part
%f Format as floating point value
%e Format as floating point value as scientific notation
%g Format as most compact form of either %f or %e
%c Print single character
\n Insert new line in output string
\t Insert tab in output string
\\ Print slash
%% Print percentage sign.
MATLAB
Description
function
char Places each string into a row of a matrix and pad each row with blanks
celldisp Display to the command window the contents of a cell array
cellstr Creates a cell array of strings from a character array
disp Displays text or an array to the command window
fprintf Writes formatted data to a file or to the command window
input Requests user input from the command window
int2str Converts an integer or an array of integers to a string
num2str Converts a number or an array of numbers to a string
sprintf Formats data and converts the formatted data to a string
xlsread Reads a Microsoft Excel file
Exercises:
1 Generate a script that converts from the English length unit of feet to the metric unit
of meter. (1 feet=0.3048 meter)
CW: Enter the value of length in feet: 11.4
11.4 ft = 3.4747 m
2 Calculate the area of circle while radius is given by user.
CW: Enter the radius of circle: 5
The area of circle is: 78.5398
3 Generate a script that converts a positive integer less than 252 (4.5036 * 10^15) to a
binary number. The MATLAB function that performs the conversion is dec2bin,
whose argument is the decimal number and whose output is a string of the binary
equivalent
CW: Enter a positive integer < 4.5x10^15: 37
The binary representation of 37 is 100101
4 Write a script file that give you conversion of temperature from Celsius to Fahrenheit.
(Use conversion formula as T( ̊C)=(5/9)(F-32)
CW: Enter the temperature in Celsius: -40
-40 Celsius= -40 Fahrenheit
5 Write a script file that give you Hypotenuse of right angle triangle while short leg and
long leg is given by user. Also calculate angle between short leg and Hypotenuse.
CW: Enter the short leg length: 3
Enter the long leg length: 4
The length of Hypotenuse is 5 and angle between short leg
and Hypotenuse is 53.13̊
6 Write a script file that take your Full name, Branch and college name as input and
store it into nm, branch and college variables respectively. Then make a row vector
of strings
CW: Enter your name: Soni Patel
Enter your Branch: Mechanical Engineering
Enter your college name: Birla Vishvakarma
Mahavidyalaya
Student details=
‘Soni Patel ’
‘Mechanical Engineering ’
‘Birla Vishvakarma Mahavidyalaya’
7 Generate a script that displays the magnitude and phase angle in degrees of a
complex number.
CW: Enter the real part of a complex number: -7
Enter the imaginary part of a complex number: 13
The magnitude and phase of -7+13i is Magnitude = 14.7648 Phase
angle = 118.3008 degrees
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Logical Branching
Experiment No: 5
Date:
Objective: To learn program flow control using various types of logical branching
Theory:
If statement is used with else and end statements. If condition#1 is true then it
will executes statement#1 and otherwise it will executes the statements in the else
part.
If condition#1 Age=input(‘Enter your Age=\n’)
statement#1 If Age>18
else fprintf(‘You are eligible to Vote’)
statement#2 else
end fprintf(‘You Can’t Vote’)
end
if condition#1 x = 10;
expressions#1 minVal = 2;
maxVal = 6;
elseif condition#2
if (x >= minVal) && (x <= maxVal)
expressions#2 disp('Value within specified
... range.')
elseif (x > maxVal)
elseif disp('Value exceeds maximum
expressions#n value.')
else else
expression#n+1 disp('Value is below minimum
end value.')
end
Switch
A switch block conditionally executes one set of statements from several choices.
Each choice is covered by a case statement.
An evaluated switch_expression is a scalar or string.
An evaluated case_expression is a scalar, a string or a cell array of scalars or strings.
The switch block tests each case until one of the cases is true. A case is true when
For numbers, eq(case_expression,switch_expression).
For strings, strcmp(case_expression,switch_expression).
For objects that support the eq(case_expression,switch_expression).
For a cell array case_expression, at least one of the elements of the cell array
matches switch_expression, as defined above for numbers, strings and objects.
When a case is true, MATLAB executes the corresponding statements and then exits
the switch block.
The otherwise block is optional and executes only when no case is true.
The MATLAB switch statement does not fall through like a C language switch
statement. If the first case statement is true, MATLAB does not execute the other case
statements.
Structure of Switch
switch switch_expression grade = input('Enter the grade
case case_expression #1 from\n A\n B\n C\n D\n F','s');
statements #1 switch(grade)
case case_expression #2 case 'A'
statements #2 fprintf('Excellent!\n' );
. . . case 'B'
case case_expression #n fprintf('Well done\n' );
statements #n case 'C'
otherwise fprintf('Good\n' );
statements #n+1 case 'D'
end fprintf('You passed\n' );
case 'F'
fprintf('Better try
again\n' );
otherwise
fprintf('Invalid grade\n' );
end
Exercises:
1 Write a MATALAB script file to check a given number is positive or negative.
2 Write a script file to check given number is odd or even.
3 Write a script file to find out the maximum out of three numbers.
4 Write a script file to implement simple calculator using if else.
CW: Enter the first number 10
Enter the second number -5
Press 1 for summation
Press 2 for Subtraction
Press 3 for Multiplication
Press 4 for Division 4
Division of 10 and -5 is -2
5 Write a MATLAB Program to create script file that give the day on the
particular date of August-2018 using if else and switch.
CW:
Enter the date of the month of August 2018 :13
There is Monday on August 13
6 Find the solution of given function using if else statements
0 𝑥<0
𝑥 0≤𝑥≤1
f(x)={ }
2−𝑥 1<𝑥≤2
0 𝑥>2
7 Write MATLAB Program for N<100 to check weather given no N is prime or
not.
Enter the number N<100: 56
Given number is not a prime number
8 Write a program to display bar chart or pie chart when input is given by user in
vector form. Bar and Pie chart required vector input.
CW:
Enter the data of chart in vector form that you want to
print : [20 30 40 10]
Enter the type of chart you want to plot bar or pie bar
% The chart should be displayed.
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Loops
Experiment No: 6
Date:
Theory:
For Loop
While Loop
The while loop repeats one or more statements an indefinite number of times, leaving
the loop only when a specified condition has been satisfied.
The while loop is typically used when the number of times one is going to use the loop
is not known. If you inadvertently create an infinite loop (that is, a loop that never ends
on its own), stop execution of the loop by pressing Ctrl+C.
If the conditional expression evaluates to a matrix, MATLAB evaluates the statements
only if all elements in the matrix are true (nonzero). To execute statements if any
element is true, wrap the expression in the any function.
When nesting a number of while statements, each while statement requires an end
keyword.
The break statement exits for or while loop completely. To skip the rest of the
instructions in the loop and begin the next iteration, use a continue statement. Break
is not defined outside for or while loop. To exit a function, use return.
Structure of While Loop
n =input('Enter Number');
while condition f = n;
statements while n > 1
end n = n-1;
f = f*n;
end
fprintf('%5d! =%5d',a,f)
Exercises:
1. Write a script file that give you series from 1 to 0 with the step size of 0.1.(Use
format rat to display it in rational number)
2. Write a script file that give you table of N<10 up to 10 where N is given by user.
CW: Enter the number N<10=9
9 * 1 = 9
9 * 2 = 18
…
9 * 10 = 90
3. Write a script file that give you sum of all the elements of vector given by
user.(use length command)
A)Sum of all elements
CW: Enter the vector : [2 5 1 -5 0 1 3 ]
Sum of all the elements is: 7
B) Sum of all elements up to negative terms
CW: Enter the vector : [2 5 1 -5 0 1 3 ]
Sum of all the elements is: 8
C) Sum of all elements excluding negative elements
CW: Enter the vector : [2 5 1 -5 0 1 3 ]
Sum of all the elements is: 7
4. For N <12, generate a script that displays n!, n = 1, 2, . . . ,N and the sum of these
factorials as shown for N = 4.
CW: Enter an integer N< 12: 4
For n = 1, 1! = 1
For n = 2, 2! = 2
For n = 3, 3! = 6
For n = 4, 4! = 24
The sum of these 4 factorials = 33
5. Write a script file that give you Hilbert matrix of dimension N where N is given
by user.
For Hilbert matrix H(i,j)=1/(i+j-1)
CW: Enter the dimension of square matrix N : 2
1 0.5
0.5 0.33
6. Write a script file that prints number, its square and its cube less than 1000
CW:
1 1 1
2 4 8
. . .
9 81 729
7. Infinite Loop: Check this Program for infinite loop and stop it using ctrl +C
i=1;
while i>0
i=i+1
end
8. Write a script file that ask number from user, verify that number whether the
number is negative or not and compute its factorial.
9. Write a script file that print Armstrong Number between 100 to 999
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Functions
Experiment No: 7
Date:
Objective: To develop user defined functions and understand use of MATLAB functions.
Theory:
A function is a group of statements that together perform a task. Functions used in any
programming environment is used for following reasons:
1. Avoid duplicate code.
2. Limit the effect of changes to specific sections of a program.
3. Promote program reuse.
4. Reduce the complexity of the overall program by making it more readable and
manageable.
5. Isolate complex operations.
6. Improve portability.
7. Make debugging and error isolation easier.
8. Improve performance because each function can be “optimized.”
The compartmentalization brought about by the use of functions also tends to minimize
the unintended use of data by portions of the program, because data to each function is
provided only on a need-to-know basis.
The function in MATLAB can be created in several ways. The most general form is the
function file, which is created by the function keyword, saved in a file, and
subsequently accessed by scripts and functions or from the command window.
However, a function cannot be created in the command window.
A function that is going to reside in a function file has at least two lines of program
code, the first line having a format required by MATLAB. Terminating character or
expression for the function program such as the end statement, which is required for
the for, while, if and switch structures is not mandatory. Furthermore, the name
of the M-file must be the same as the name of the primary function, except that the file
name has the extension “.m”.
The number of variables and their type (scalar, vector, matrix, string, cell, function
handle) that are brought in and out of the function are controlled by the function
interface, which is the first non-comment line of the function program. In general, a
function will consist of the interface line, some comments and one or more expressions
as shown below. The interface has the general form given in the first line.
function [OutputVariables] = FunctionName(InputVariables)
% Comments
Expressions
OutputVariables = . . .
OutputVariables is a comma-separated list of the names of the output variables,
InputVariables is a comma-separated list of the names of the input variables, and
FunctionName is the name of the function and in the case of a primary function,
the name of the function M-file. It must begin with an upper or lower case letter and
has the same restrictions as for variable names. The first word of this statement,
function, is a reserved word that may only be used in this context.
The function file may be stored in any directory to which a path has been or will be
defined and has the file name FunctionName.m. However, in order for one to have
access to this function during a session, the function and the script must have their
respective paths known to the system. This is done by either having the script and
function in the current directory, or by placing the function’s directory in a path that
has been saved.
The comments immediately following the function interface statement are used by
MATLAB to create this function’s Help information—that is, when one types at the
command line
help FunctionName
All the initial contiguous comments will appear in the MATLAB command window.
Any comments appearing prior to the function statement will not be part of the Help
information. The Help information ends when no more contiguous comment lines are
encountered, that is, when a blank line or an executable expression is encountered.
Note: A function can have no InputVariables and/or OutputVariables as a special
cases for special purposes.
Sub-function
When the function keyword is used more than once in a function file, all the additional
functions created after the first function keyword are called subfunctions. The
expressions comprising the first use of the function keyword is called the primary
function. It is the only function that is accessible from the command window, scripts, and
other functions residing in their own M-file. The subfunctions are accessible only to the
primary function and to other subfunctions within the primary function file.
We shall illustrate the use of a primary function and subfunctions by computing the mean
and standard deviation of a vector of numerical values. We shall compute
𝑚
1
𝑚 = ∑ 𝑥𝑘
𝑛
𝑘=1
𝑚 1/2
1
𝑠=[ (∑ 𝑥𝑘 2 − 𝑛𝑚2 )]
𝑛−1
𝑘=1
We shall call the primary function MeanStdDev, the subfunction that computes the mean
𝑚 meen, and the subfunction that computes the standard deviation 𝑠 stdev. The primary
function and its subfunctions are saved in a file MeanStdDev.m. The primary function and
subfunctions are then given by the following program:
function [m, s] = MeanStdDev(dat) % Primary function
n = length(dat);
m = meen(dat, n);
s = stdev(dat, n);
v = [1, 2, 3, 4];
[m, s] = MeanStdDev(v)
Anonymous function
Anonymous functions are a means of creating functions for simple expressions without
having to create M-files or subfunctions. It can be composed of only one expression,
and it can bring back only one variable—that is, the form [u, v] on the left-hand side
of the equal sign is not allowed. Thus, any function requiring logic or multiple
operations to arrive at the result cannot employ the anonymous function. The general
form of an anonymous function is
functionhandle = @(arguments)(expression)
For example, create a handle to an anonymous function that finds the square of a
number:
sqr = @(x) x.^2;
a = sqr(5)
a =
25
Inline function
Another way to create a local function, either in the command window, a script, a
primary function, or subfunction is by using inline. Like the anonymous function,
this function also doesn’t have to be saved in a separate file. However, it does have
several limitations. It cannot call another inline function, but it can use a user-created
function existing as a function file. Like the anonymous function it can be composed
of only one expression and can bring back only one variable. Thus, any function
requiring logic or multiple operations to arrive at the result cannot employ inline.
The general form of inline is
FunctionName = inline('expression', 'v1','v2', . . .)
where expression is any valid MATLAB expression and v1,v2,..
are the names of all the variables appearing in expression. The single quotation
marks are required as shown.
We illustrate inline with the following example. Let us create a function FofX that
evaluates
𝑓(𝑥) = 𝑥 2 cos(𝑎𝑥) − 𝑏
g =
-1.5483 -1.7259
The inline form for functions, just as for the anonymous function, has utility in many
MATLAB functions that require one to first create a function that will be evaluated
subsequently by that MATLAB function.
Function Descriptions
polyfit Fits a polynomial to an array of values.
polyval Evaluates a polynomial at an array of values
spline Applies cubic spline interpolation to arrays of coordinate values
interp1 Interpolates between pairs of coordinate values
trapz Approximates an integral from an array of amplitude values
polyarea Determines the area of a polygon
Exercise:
2D Plotting
Experiment No: 8
Date:
Theory:
It can sometimes be useful to display multiple plots on the same figure for comparison.
This can be done using the subplot function that takes arguments for number of rows
of plots, number of columns of plots, and plot number currently being plotted:
Example:
clear all
close all
% subplot (nrows,ncols,plot_number)
x=0:.1:2*pi; % x vector from 0 to 2*pi, dx = 0.1
subplot(2,2,1); % plot sine function
plot(x,sin(x));
subplot(2,2,2); % plot cosine function
plot(x,cos(x));
subplot(2,2,3) % plot negative exponential function
plot(x,exp(-x));
subplot(2,2,4); % plot x^3
plot(x, x.^3);
To create a simple line plot and add a text box annotation to the figure, specify the text
description by setting the String property. Force the box to fit tightly around the text by
setting the FitBoxToText property to 'on'.
plot(1:10)
dim = [.2 .5 .3 .3];
str = 'Straight Line Plot from 1 to 10';
annotation('textbox',dim,'String',str,'FitBoxToText','on');
Create a text box annotation without setting the FitBoxToText property, the text box
uses the specified width and height and wraps text as needed.
plot(1:10)
dim = [.2 .5 .3 .3];
str = 'Straight Line Plot from 1 to 10';
annotation('textbox',dim,'String',str)
Create a text box annotation with multiline text by setting the String property to a cell
array. Each element of the cell array displays on a separate line. Force the box to fit
tightly around the text by setting the FitBoxToText property to 'on'.
figure
plot(1:10)
dim = [0.2 0.5 0.3 0.3];
str = {'Straight Line Plot','from 1 to 10'};
annotation('textbox',dim,'String',str,'FitBoxToText','on');
Exercise:
1. To draw a circle of radius whose center is located at (a,b) in a Cartesian coordinate
system, one has to first transform the radial coordinates to Cartesian coordinates using
𝑥 = 𝑎 + 𝑟𝑐𝑜𝑠(𝜃)
𝑦 = 𝑏 + 𝑟𝑠𝑖𝑛(𝜃)
where, 0 ≤ 𝜃 ≤ 2𝜋
2. Plot a 2D graph for following
𝑦 = 𝑎2 2 − 𝑥 2
for −5 ≤ 𝑥 ≤ 5 and 𝑎 = 1,2 … 5
3. Plot graph for following three mathematical relations.
𝑔1 (𝑥) = 0.1𝑥 2
𝑔2 (𝑦) = 𝑐𝑜𝑠 2 𝑦
𝑔3 (𝑧) = 𝑒 −0.3𝑧
where 0 ≤ 𝑥, 𝑦 𝑎𝑛𝑑 𝑧 ≤ 3.5.
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
3D Plotting
Experiment No: 9
Date:
Theory:
Lines in 3D
where uj, vj and wj are the 𝑥-, 𝑦-, and 𝑧-coordinates, respectively, of a point.
They are scalars, vectors of the same length, matrices of the same order, or expressions
that, when evaluated, result in one of these three quantities. The quantity cj is a string
of characters, where one character specifies the color, one character specifies the point
s characteristics, and where up to two characters specify the line type. To draw a set of
n unconnected lines whose end points are (x1j,y1j,z1j ) and (x2j,y2j,z2j), j =1,2,3 …n , we
create six vectors
xj = [ x1j x2j x3j ….. xnj ]
yj = [ y1j y2j y3j ….. ynj ]
xj = [ z1j z2j z3j ….. znj ]
returns 3-D grid coordinates defined by the vectors x, and y. The grid represented
by X, and Y has size length(y)-by-length(x).
[X,Y,Z] = meshgrid(x,y,z)
returns 3-D grid coordinates defined by the vectors x, y, and z. The grid represented
by X, Y, and Z has size length(y)-by-length(x)-by-length(z).
Surfaces
where x and y are the coordinates in the 𝑥𝑦-plane and z is the resulting height.
The basic surface plotting functions are
surf(x, y, z) and
mesh(x, y, z)
where the x, y and z are the coordinates of the points on the surface. The
function surf draws a surface composed of colored patches, whereas mesh draws
white surface patches that are defined by their boundary. In surf, the colors of the
patches are determined by the magnitude of z, whereas it is the colors of the lines in
mesh that are determined by the magnitude of z. In both surf and mesh, hidden lines
are removed. The hidden lines can be displayed in mesh by using
hidden off
We shall illustrate the use of these functions, and several other functions, with the
plotting of the surface created by
𝑧(𝑥, 𝑦) = 𝑥 4 + 3𝑥 2 + 𝑦 2 − 2𝑥 − 2𝑦 − 2𝑥 2 𝑦 + 6
over the range −3 < 𝑥 < 3 and −3 < 𝑦 < 13.We shall place the generation of the
𝑥-, 𝑦-, and 𝑧-coordinate values in a function M file called SurfExample. Thus,
function [x, y, z] = SurfExample
x1 = linspace(-3, 3, 15);
y1 = linspace(-3, 13, 17);
[x, y] = meshgrid(x1, y1);
z = x.^4+3*x.^2-2*x+6-2*y.*x.^2+y.^2-2*y;
Using SurfExample, the differences between mesh, surf, and mesh without using
the hidden line removal option are shown in Table 4
Table 2 Illustration of the Difference between surf, mesh, and mesh without Hidden Line
Removal
mesh [x, y, z] =
SurfExample;
mesh(x, y, z)
mesh [x, y, z] =
SurfExample;
hidden mesh(x, y, z)
off hidden off
Exercises:
Sorting Algorithms
Experiment No: 10
Date:
Objective: To understand sorting techniques (insertion sort, selection sort and bubble sort)
using MATLAB.
Theory:
A sorting algorithm is an algorithm made up of a series of instructions that takes
an array as input, performs specified operations on the array, sometimes called a list,
and outputs a sorted array.
In other words, a sorted array is an array that is in a particular order. For
example, [𝑎, 𝑏, 𝑐, 𝑑] is sorted alphabetically, [1,2,3,4,5] is a list of integers sorted in
increasing order, [5,4,3,2,1] and is a list of integers sorted in decreasing order.
1. Selection sort
2. Bubble sort
3. Insertion sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place
comparison-based algorithm in which the list is divided into two parts, the sorted part
at the left end and the unsorted part at the right end. Initially, the sorted part is empty
and the unsorted part is the entire list. (Refer Lecture note for more details.)
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order. (Refer Lecture note for more details.)
Insertion sort is an in-place comparison-based sorting algorithm. Here, a sub-list is
maintained which is always sorted. For example, the lower part of an array is
maintained to be sorted. An element which is to be 'insert'ed in this sorted sub-list, has
to find its appropriate place and then it has to be inserted there. Hence the
name, insertion sort. (Refer Lecture note for more details.)
Exercises:
1. Write a MATLAB user-friendly script which accepts an array (which may contain
either numeric value or string of character) from the user and sort it using Selection
sort algorithm.
2. Write a MATLAB user-friendly script which accepts an array (which may contain
either numeric value or string of character) from the user and sort it using Bubble
sort algorithm.
3. Write a MATLAB user-friendly script which accepts an array (which may contain
either numeric value or string of character) from the user and sort it using Insertion
sort algorithm.
4. Write a MATLAB script which compares all three algorithms.
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Searching Algorithms
Experiment No: 11
Date:
Theory:
There are two types of search algorithms: algorithms that don’t make any assumptions
about the order of the list, and algorithms that assume the list is already in order.
Linear search
The simplest search algorithm is sequential search, also known as linear search. In
this method, the target number that is being sought is compared with the first member
of the database, then with the second, etc., until either the number is found, or the end
of the database is reached, whichever comes first.
In linear search, we look at each item in the list in turn, quitting once we find an item
that matches the search term or once we’ve reached the end of the list. Our “return
value” is the index at which the search term was found, or some indicator that the search
term was not found in the list. (Refer Lecture note for more details.)
Binary search:
If a list has been sorted before the search is undertaken, searches can be carried out
much more quickly. The search method that should be used on a sorted list is the binary
search. It is more complicated than the sequential search method, but the complication
is well worth it: A binary search requires no more than 40 comparisons to find a number
in a list of one million numbers!
If our list is already in order, for example, think about looking up a name in the phone
book. It makes more sense to exploit the ordering of the names, start our search
somewhere near the starting alphabet, and refine the search from there rather than by
starting at the beginning and looking at each name in turn.
Binary search exploits the ordering of a list. The idea behind binary search is that each
time we make a comparison, we eliminate half of the list, until we either find the search
term or determine that the term is not in the list. We do this by looking at the middle
item in the list, and determining if our search term is higher or lower than the middle
item. If it’s lower, we eliminate the upper half of the list and repeat our search starting
at the point halfway between the first item and the middle item. If it’s in higher, we
eliminate the lower half of the list and repeat our search starting at the point halfway
between the middle item and the last item. (Refer Lecture note for more details.)
Exercises:
1. Write a MATLAB user-friendly script which accepts an array (which may contain
either numeric value or string of character) to search within and a value to be searched
from the user and search using linear search algorithm.
2. Write a MATLAB user-friendly script which accepts an array (which may contain
either numeric value or string of character) to search within and a value to be searched
from the user and search using Binary search algorithm.
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Objective: To understand bracketing methods and open methods to find root of single variable
equation.
Theory:
There are following bracketing methods: (i) Bisection Method, and (ii) False-position
Method.
Bisection Method:
Consider a transcendental equation f(x) = 0 which has a zero (solution) in the interval
[xl; xu] and f(xl)*f(xu)<0. Bisection scheme computes the zero, say c, by repeatedly
halving the interval [xl; xu].That is, starting with xr = (xl + xu) / 2; the interval [xl; xu] is
replaced either with [xl; xu] or with [xl; xr] depending on the sign of f(xl)*f(xr). This
process is continued until the zero is obtained. Since the zero is obtained numerically
the value of xrmay not exactly match with all the decimal places of the analytical
solution of f(x)=0 in the interval[xl; xu]. (Refer Lecture note for more details.)
False-position Method
A shortcoming of the bisection method is that, in dividing the interval from xl to xuinto
equal halves, no account is taken of the magnitudes of f(xl) and f(xu). For example,if
f(xl) is much closer to zero than f(xu), it is likely that the root is closer to xl than toxu.
An alternative method that exploits this insight is to join f(xl)and f(xu) by a straight line.
The intersection of this line with the x axis represents animproved estimate of the root.
The fact that the replacement of the curve by a straightline gives a “false position” of
the root is the origin of the name, method of false position,or in Latin, regulafalsi. It is
also called the linear interpolation method. (Refer Lecture note for more details.)
Two simplest open methods to find a root of single variable equation in the discussion.
(i) Newton-Rapson Method and (ii) Secant method.
Newton-Rapson Method:
𝑓(𝑥0 )
𝑥1 = 𝑥0 −
𝑓′(𝑥0 )
Geometrically, (𝑥1 , 0) is the intersection with the x-axis of the tangent to the graph of
𝑓at (𝑥0 , 𝑓(𝑥0 )). The process is repeated as
𝑓(𝑥𝑖 )
𝑥𝑖+1 = 𝑥𝑖 −
𝑓′(𝑥𝑖 )
until a sufficiently accurate value is reached. (Refer Lecture note for more details.)
Secant Method:
𝑓(𝑥𝑖−1 ) − 𝑓(𝑥𝑖 )
𝑓′(𝑥𝑖 ) ≅
𝑥𝑖−1 − 𝑥𝑖
This approximation can be substituted into Newton-Rapson equation to yield the
following iterative equation: (Refer Lecture note for more details.)
𝑓(𝑥𝑖 )(𝑥𝑖−1 − 𝑥𝑖 )
𝑥𝑖+1 = 𝑥𝑖 −
𝑓(𝑥𝑖−1 ) − 𝑓(𝑥𝑖 )
Exercise:
1. Find the real root of following equations by bisection and false method correct to four
decimal places.
e. 𝑥 3 − 4𝑥 − 9 = 0 [2,3]
f. 𝑥 − cos 𝑥 = 0 [0,1]
2. Find the real root of following equations by Newton-Rapson and Secant method correct
to four decimal places.
e. 𝑥 3 − 4𝑥 − 9 = 0 3 [3,3.5]
f. 𝑥 − cos 𝑥 = 0 1 [1,2]
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers
Interpolation of data
Experiment No: 13
Date:
Curve fitting may have been to determine intermediate values from tabulated data—for
instance, from interest tables for engineering economics or from steam tables for
thermodynamics. Although many of the widely used engineering properties have been
tabulated, there are a great many more that are not available in this convenient form.
Special cases and new problem contexts often require that you measure your own data
and develop your own predictive relationships. Two types of applications are generally
encountered when fitting experimental data: trend analysis and hypothesis testing.
Trend analysis represents the process of using the pattern of the data to make predictions
& in hypothesis testing, an existing mathematical model is compared with measured
data.In addition to the above engineering applications, curve fitting is important in other
numerical methods such as integration and the approximate solution of differential
equations. Finally, curve-fitting techniques can be used to derive simple functions to
approximate complicated functions.
>>p = polyfit(x,y,n)
Description
p = polyfit(x,y,n) finds the coefficients of a polynomial p(x) of degree n that fits
the data, p(x(i)) to y(i), in a least squares sense. The result p is a row vector of length
n+1 containing the polynomial coefficients in descending powers:
p(x) = p1xn + p2xn-1 + ….. + pnx + pn+1
[p,S] = polyfit(x,y,n) returns the polynomial coefficients p and a structure S
for use with polyval to obtain error estimates or predictions.
Example:
Given f(x) 1/x find the interpolating polynomial approximate the value of 1.5
X 2 4 5
f(x) 0.5 0.25 0.2
>>lagrange(x,y,a)
Description
Determines the coefficients of the Lagrange interpolating polynomial p(x) and
computes p(a) INPUTS: The vectors x and y and the value a
Example:
Use lagrange.m function to find the Lagrange interpolating polynomial and
approximate the value of 1.5
X 0 1 2 3
Y -5 -6 -1 16
>>x=[0 1 2 3];
>>y=[-5 -6 -1 16];
>>lagrange(x,y,1.5);
Exercise:
1. Use the data of the table below and the appropriate polynomial equation using poyfit
and lagrange functions. Find y(50.2) and y(55.9) using the polynomial in each case.
x 50 51 52 53 54 55 56
y 7.071 7.141 7.211 7.280 7.384 7.416 7.483
2. Use the data of the table below and the appropriate polynomial equation using poyfit
and lagrange functions. Find y(1.3) and y(1.95) using the polynomial in each case.
x 1.1 1.2 1.5 1.7 1.8 2.0
y=f(x) 1.112 1.291 1.636 2.054 2.323 3.011