ES106 Manual - 2022-23

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

BIRLA VISHVAKARMA MAHAVIDYALAYA

VALLABHVIDYANAGAR

ES106
Programming For Engineers
Lab Manual
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR

VISION and MISSION of our College

VISION:-
"Produce globally employable innovative engineers with core
values”

MISSION:-

1. Re-engineer curricula to meet global employment


requirements.
2. Promote innovative practices at all levels.
3. Imbibe core values.
4. Reform policies, systems and processes at all levels.
5. Develop faculty and staff members to meet the challenges
Name: _________________________________________ ID. No.: ____________

Division: _______ Batch: __________ Semester: _____ Year: ______________

INDEX

Ex. Page
Date Title Marks Faculty Sign
No. No.

1. Introduction to MATLAB

2. Arithmetic Expressions

3. Vector and Matrices

4. Data Input and Output

5. Logical Branching

6. Loops

7. Functions

8. 2D Plot

9 3D Plot

10. Sorting Algorithms

11. Searching Algorithms

12. Root of Equation with single variable

13. Interpolation

14. Numerical Differentiation

15. Numerical Integration


BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers

Introduction to MATLAB
Experiment No: 1
Date:

Objective: To get familiarized with MATLAB programming environment

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:

 The Command Window


 The Command History
 The Workspace
 The Current Directory
 The Help Browser
 The Start button
Using MATLAB as a calculator

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.

Symbol Operation Example


+ Addition 2+3
- Subtraction 2-3
* Multiplication 2*3
/ Division 2/3

MATLAB variables are created with an assignment statement. The syntax of variable
assignment is
variable name = a value (or an expression)
For example,

>> 𝑥 = 𝑒𝑥𝑝𝑟𝑒𝑠𝑠𝑖𝑜𝑛

where expression is a combination of numerical values, mathematical operators, variables, and


function calls. On other words, expression can involve:

 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

>> help Command


Use on-line help to request info on a specific function
>> help sqrt

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.

cos(x) Cosine abs(x) Absolute value


sin(x) Sine sign(x) Signum function
tan(x) Tangent max(X) Maximum value
acos(x) Arc cosine min(x) Minimum value
asin(x) Arc cosine ceil(x) Round towards +∞
atan(x) Arc tangent floor(x) Round towards -∞
exp(x) Exponential round(x) Round to nearest integer
sqrt(x) Square root rem(x) Remainder after division
log(x) Natural logarithm angle(x) Phase angle
log10(x) Common logarithm conj(x) Complex conjugate

Commonly used commands

>> clc : to clear command window


>> who : list variables in the current workspace
>> whos : along with list of variables it give information like size , number of bytes , type
>> clear : clears variable from the current workspace.

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

Draw Plot for following example;


Descriptio
Command Output(Results)
n
Create an
x-array of
100
X=linespace(0,4*pi,10 X=
samples
0) [0 …….]
between 0
and 4π.

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:

Objective: To execute arithmetic operations in MATLAB.

Theory:

Arithmetic expressions

MATLAB allows you to do simple computational problems using arithmetic expressions.


The following table shows the list of Arithmetic Operators used in MATLAB:
Symbol Operation Example
+ Addition 2+3
- Subtraction 2-3
* Multiplication 2*3
/ Division 2/3
1. Simple example of using arithmetic expression
The following examples show the use of arithmetic operators on scalar data. Create a script file
with the following code.
Steps for creating new script: File -> New Script -> filename.m

𝑎 = 𝑖𝑛𝑝𝑢𝑡(‘𝑒𝑛𝑡𝑒𝑟 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑎’);

𝑏 = 𝑖𝑛𝑝𝑢𝑡(‘𝑒𝑛𝑡𝑒𝑟 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑏’);

𝑐 = 𝑎 + 𝑏
𝑑 = 𝑎 − 𝑏
𝑒 = 𝑎 ∗ 𝑏
𝑓 = 𝑎/𝑏
𝑔 = 𝑎\𝑏
𝑥 = 7;
𝑦 = 3;
𝑧 = 𝑥^𝑦

When you run the file, it produces the following result –


𝑒𝑛𝑡𝑒𝑟 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑎 10
𝑒𝑛𝑡𝑒𝑟 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑏 20
𝑐 = 30
𝑑 = −10
𝑒 = 200
𝑓 = 0.50000
𝑔 = 2
𝑧 = 343

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

Vectors and Matrices


Experiment No: 3
Date:

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.

Vectors: Column and Row Matrices

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 𝑎𝑚

The quantity 𝑚 is the length of the vector.

When 𝑎𝑖𝑗 = 𝑎1𝑗 , that is, there is only one row, then is called a row matrix or a vector,
that is,

𝑎 = [𝑎11 𝑎12 ⋯ 𝑎1𝑛 ] = [𝑎1 𝑎2 ⋯ 𝑎𝑛 ] → (1 × 𝑛)

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

Vectors in MATLAB are expressed as either


𝑥 = [𝑎 𝑝 𝑧] 𝑜𝑟 𝑥 = [𝑎, 𝑝, 𝑧]

where 𝑎, 𝑝, 𝑧, ⋯ are either variable names, numbers, expressions, or strings.

Colon Notation

The colon notation to create a vector is

𝑥 = 𝑠: 𝑑: 𝑓 𝑜𝑟 𝑥 = (𝑥: 𝑑: 𝑓) 𝑜𝑟 𝑥 = [𝑠: 𝑑: 𝑓]

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.

𝑥 = [𝑠, 𝑠 + 𝑑, 𝑠 + 2𝑑, ⋯ , 𝑠 + 𝑛𝑑]

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

Consider the following (4 × 3) matrix:


𝑎11 𝑎12 𝑎13
𝑎21 𝑎22 𝑎23
𝐴 = [𝑎 𝑎32 𝑎33 ] → (4 × 3)
31
𝑎41 𝑎42 𝑎43

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

𝐴 = [𝑎11 𝑎12 𝑎13 ; ⋯

𝑎21 𝑎22 𝑎23 ; ⋯

𝑎31 𝑎32 𝑎33 ; ⋯

𝑎41 𝑎42 𝑎43 ]


where the ellipses (⋯ )are required to indicate that the expression continues on the next line.
One can omit the ellipsis (⋯ ) and instead use the Enter key to indicate the end of a row. In
this case, the expression will look like

𝐴 = [𝑎11 𝑎12 𝑎13 ;

𝑎21 𝑎22 𝑎23 ;

𝑎31 𝑎32 𝑎33 ;

𝑎41 𝑎42 𝑎43 ]

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 = [𝑎11 𝑎12 𝑎13 ];

𝑣2 = [𝑎21 𝑎22 𝑎23 ];

𝑣3 = [𝑎31 𝑎32 𝑎33 ];

𝑣4 = [𝑎41 𝑎42 𝑎43 ];

𝐴 = [𝑣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.

MATHEMATICAL OPERATIONS WITH MATRICES


We now define several fundamental matrix operations: addition, subtraction, multiplication,
inversion, determinants, solutions of systems of equations, and roots (eigenvalues).These
results are then used to obtain numerical solutions to classes of engineering problems.

Addition and Subtraction

If we have two matrices 𝐴 and 𝐵, each of the order (𝑚 × 𝑛), then

𝑎11 + 𝑏11 𝑎12 + 𝑏12 ⋯ 𝑎1𝑛 + 𝑏1𝑛


𝑎21 + 𝑏21 𝑎22 + 𝑏22 ⋯ 𝑎2𝑛 + 𝑏2𝑛
𝐴±𝐵 =[ ] → (𝑚 × 𝑛)
⋮ ⋮ ⋱ ⋮
𝑎𝑚1 + 𝑏𝑚1 𝑎𝑚2 + 𝑏𝑚2 ⋯ 𝑎𝑚𝑛 + 𝑏𝑚𝑛

Multiplication

If we have a matrix 𝐴 in order (𝑚 × 𝑘) and a matrix 𝐵 in order (𝑘 × 𝑛), then


𝑐11 𝑐12 ⋯ 𝑐1𝑛
𝑐21 𝑐22 ⋯ 𝑐2𝑛
𝐶 = 𝐴𝐵 = [ ⋮ ⋮ ⋱ ⋮ ] → (𝑚 × 𝑛)
𝑐𝑚1 𝑐𝑚2 ⋯ 𝑐𝑚𝑛
where
𝑘

𝑐𝑙𝑝 = ∑ 𝑎𝑙𝑗 𝑏𝑗𝑝


𝑗=1

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.

MATLAB function Description


length Determines length of vector
size Determines size of matrix
det Determinant of a square matrix
diag Diagonal of a square matrix, creates a
diagonal matirx
dot Dot product of two vectors
end Last index in an array
eye Creates the identity matrix
inv Inverse of a square matrix
length Length of a vector
linsolve Solves linear system of equation
linspace Creates equally spaced elements of a vector
logspace Creates equally spaced elements of a vector
on log10 𝑥 scale
magic Creates a square matrix whose sum of each
row, each columns, and diagonals is equal
max Determines the maximum value in an array
min Determines the minimum value in an array
ones Creates an array whose elements equal 1
size Size of an array
sort Sorts elements of an array in ascending order
sum Sums elements of an array
zeros Creates an array whose elements equal 0

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:

8𝑥1 + 𝑥2 + 6𝑥3 = 7.5

3𝑥1 + 5𝑥2 + 7𝑥3 = 4

4𝑥1 + 9𝑥2 + 2𝑥3 = 12


BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers

Data Input and Output


Experiment No: 4
Date:

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.

Basic Useful Command:

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… else” Statement

 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

The condition can be written using operator/s listed in Table 1.

Table 1 List of Condition Operators in MATLAB

Condition Mathematics MATLAB


AND & &&
Less than or Equal ≤ <=
Greater than or Equal ≥ >=
Equal = ==
Not equal ≅ ~=

If… elseif …else Statement

 If statement is a conditional statement that branches to different parts of its Structure


depending on the satisfaction of conditional expressions.
 If condition#1 is satisfied then expressions 1 will executes and followed by
end. If first condition is not satisfied then it will go for second condition#2 with
help of elseif and if satisfied then executes the expression#2. If none of
conditions are satisfies then then it will execute else statement.
 You can nest any number of if statements. Each if statement requires an end
keyword.
 Avoid adding a space after else within the elseif keyword (else if). The space
creates a nested if statement that requires its own end keyword.

Structure of if… elseif

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:

Objective: To learn the basics of iterative problems using loops

Theory:

For Loop

 For loop repeats a group of statements a fixed, predetermined number of times. A


matching end delineates the statements.
 Avoid assigning a value to the index variable within the loop statements. The for
statement overrides any changes made to index within the loop.
 To iterate over the values of a single column vector, first transpose it to create a row
vector.

for index = values s = 10;


statements for c = 1:s
end for r = 1:s
H(r,c) = 1/(r+c-1);
end
end
H

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);

function m = meen(v, n) % Subfunction


m = sum(v)/n;
function sd = stdev(v, n) % Subfunction
m = meen(v, n); % Calls a sub function
sd = sqrt((sum(v.^2)-n*m^2)/(n-1));
 A script to illustrate the use of this function file is

v = [1, 2, 3, 4];
[m, s] = MeanStdDev(v)

Which upon execution gives


m =
2.5000
s =
1.2910

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)

where functionhandle is the function handle, arguments is a comma-


separated list of variable names, and expression is a valid MATLAB expression.
Any parameters that appear in expression and do not appear in arguments must be
given a numerical value prior to this statement. The parentheses around expression
are optional, but can be a visual aid. A function handle is a way of referencing a
function and is used as a means of invoking the anonymous function and as a means
to pass the function as an argument in functions. A function handle is constructed by
placing an “@” in front of the syntax as shown above or in front of a function name.
The function handle functionhandle also serves as the name of the function and is used
in the same manner as one does for a function created by the function keyword.

 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(𝑎𝑥) − 𝑏

where 𝑎 and 𝑏 scalars and 𝑥 is a vector. Then,


FofX = inline('x.^2.*cos(a*x)-b', 'x', 'a', 'b');
g = FofX([pi/3, pi/3.5], 4, 1)
results in

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.

MATLAB library functions


 There are many general-purpose functions in MATLAB library that have a wide range
of use in obtaining numerical solutions to engineering problems. We will consider a
subset of them and divide them into two groups: those that operate on arrays of data
(Table ) and those that require user-defined functions. Details on use of them can be
found using MATLAB help command.

Table 1 MATLAB functions operate on arrays of data

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:

1. Write a MATLAB program to read a matrix of size 𝑚 × 𝑛 from the keyboard


and display the same on the screen.
2. Write a function power1 to raise a vector or matrix A to a power B. The value
of each element of vector or matrix A is real while B is scalar integer.
3. Create function file that give you prime number between given limit.
4. Create function file that give you prime factor of given number.
5. Create function that gives you Fibonacci series up to given limit.
6. Create an inline function to represent the formula 𝑓 = 3𝑠𝑖𝑛(2𝜃) and calculate
value of function from 0 ≤ 𝜃 ≤ 2𝜋.
7. Write user defined function that will display the table of number N where N is
enter by User.
8. Write function file name cel2feh which converts the temperature in Celsius to
Fahrenheit.
9. Write a function file name conversion that convert various length unit. Write
script file that will use the defined function ’Conversion’.
10. Write function ‘Databaseofstudent’ that will stored the information like ID no,
Photo, Admission Year, address, Mobile no and display it when called.
CW: databaseofstudent(001), Information of Student with ID no 001
will be displayed.
11. Create anonymous function for following equation and perform various
arithmetic calculation on it.
a. p = 'x^2 + x – sqrt(x)';
b. q= 'x^4–5x^3+4x^2–5x+6';
c. r= ‘x(sin(x)+cos(x))^2’
d. s= ‘xlogx+e^x’
12. Write inline function that will find the solution of quadric equation when
coefficient will be defined by users.
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers

2D Plotting
Experiment No: 8
Date:

Objective: To learn to draw 2D plots in MATLAB.

Theory:

 The basic 2D plotting command is


plot(u, v, c)
where 𝑢 and 𝑣 are the 𝑥- and 𝑦-coordinates, respectively, of a point or a
series of points. Each set of 𝑢 and 𝑣 is a pair of numbers, vectors of the same
length, matrices of the same order, or expressions that, when evaluated, result
in one of these three quantities. The quantity 𝑐 is a string of characters: one
character specifies the line/point color, one character specifies the point type if
points are to be plotted, and up to two characters are used to specify the line
characteristics.
 To plot vectors 𝑋 = [3 9 27] and 𝑡 = [1 2 3] following command shall be executed in
MATLAB.
clear all % clear all previous variables
X = [3 9 27]; % my dependent vector of interest
t = [1 2 3]; % my independent vector
figure % create new figure
plot(t, X)
To give the above figure a title and axis labels:

title(‘Plot of Distance over Time’) % title


ylabel(‘Distance (m)’) % label for y axis
xlabel(‘Time (s)’) % label for x axis
 If you have plotted multiple dependent vectors on the same plot and want to distinguish
them from each other via a legend, the syntax is very similar to the axis labeling above.
It is also possible to set colors for the different vectors and to change the location of the
legend on the figure.
clear all
X = [3 9 27]; % dependent vectors of interest
Y = [10 8 6];
Z = [4 4 4];
t = [1 2 3]; % independent vector
figure
hold on % allow all vectors to be plotted in same figure
plot(t, X, ‘blue’, t, Y, ‘red’, t, Z, ‘green’)
title(‘Plot of Distance over Time’) % title
ylabel(‘Distance (m)’) % label for y axis
xlabel(‘Time (s)’) % label for x axis
legend(‘Trial 1’, ‘Trial 2’, ‘Trial 3’)
legend(‘Location’,‘NorthWest’) % move legend to upper
left

 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:

Objective: To learn how to draw 3D plots in MATLAB.

Theory:

Lines in 3D

 The 3D version of plot is


plot3(u1, v1, w1, c1 ,u2, v2, w2, c2, . . . )

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 ]

 Then, the plot3 instruction is


x1 = [ . . . ]; x2 = [ . . . ];
y1 = [ . . . ]; y2 = [ . . . ];
z1 = [ . . . ]; z2 = [ . . . ];
plot3([x1; x2], [y1; y2], [z1; z2])
where [x1; x2], [y1; y2], and [z1; z2] are each (2 × 𝑛) matrices.
This is the 3D counterpart of the 2D procedure used with plot. All annotation
procedures discussed for 2D drawings are applicable to the 3D curve- and surface-
generating functions, except that the arguments of text become
text(x, y, z, s)

where s is a string and zlabel(s1) is used to label the z-axis and s1 is a


string.

MATLAB function: meshgrid


 The meshgrid function has numerous applications in evaluating series in displaying
three-dimensional surfaces.
[X,Y] = meshgrid(x,y)

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

 A set of 3D plotting functions is available to create surfaces, contours, and variations


and specialization of these basic forms. A surface is defined by the expression
z = f (x,y)

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

Plotting Script Graph


Function
surf [x, y, z] =
SurfExample;
surf(x, y, z)

mesh [x, y, z] =
SurfExample;
mesh(x, y, z)

mesh [x, y, z] =
SurfExample;
hidden mesh(x, y, z)
off hidden off
Exercises:

1. Plot the following three-dimensional curves. Use axis equal.


Name Parameter Values Equations
Spherical Helix 𝑐 = 5.0; 0 ≤ 𝜑 ≤ 10𝜋 𝑥 = 𝑠𝑖𝑛(𝜑/2𝑐) 𝑐𝑜𝑠𝜑
𝑦 = 𝑠𝑖𝑛(𝜑/2𝑐) 𝑠𝑖𝑛𝜑
𝑧 = 𝑐𝑜𝑠(𝜑/2𝑐)
Toroidal spiral 𝑎 = 0.2, 𝑏 = 0.8, 𝑥 = [𝑏 + 𝑎 𝑠𝑖𝑛(𝑐𝜑)] 𝑐𝑜𝑠𝜑
𝑐 = 20.0; 0 ≤ 𝜑 ≤ 2𝜋 𝑦 = [𝑏 + 𝑎 𝑠𝑖𝑛(𝑐𝜑)] 𝑠𝑖𝑛𝜑
𝑧 = 𝑎 𝑐𝑜𝑠(𝑐𝜑)
Sine wave on sphere 𝑎 = 10.0, 𝑏 = 1.0, 𝑥 = 𝑐𝑜𝑠𝜑√𝑏 2 − 𝑐 2 𝑐𝑜𝑠 2 (𝑎𝜑)
𝑐 = 0.3; 0 ≤ 𝜑 ≤ 2𝜋
𝑦 = 𝑠𝑖𝑛𝜑√𝑏 2 − 𝑐 2 𝑐𝑜𝑠 2 (𝑎𝜑)
𝑧 = 𝑐 𝑐𝑜𝑠(𝑎𝜑)
2. Plot the following surfaces. Use axis equal vis3d. Use the Rotate 3D icon to get a
better understanding of the surface. In some cases, the use of shading interp will
improve the image.
Name Parameter Values Equations
Helical Spring 𝑟1 = 𝑟2 = 0.25, 𝑇 = 2, 𝑛 = 6, 𝑥 = [1 − 𝑟1 cos(𝑣)] cos(𝑢)
0 ≤ 𝑢 ≤ 2𝑛𝜋, 0 ≤ 𝑣 ≤ 2𝜋 𝑦 = [1 − 𝑟1 cos(𝑣)] sin(𝑢)
𝑧 = 𝑟2 [sin(𝑣) + 𝑇𝑢/𝜋]

Astroidal ellipsoid 𝑎 = 𝑏 = 𝑐 = 1, 𝑥 = (𝑎 𝑐𝑜𝑠𝑢 𝑐𝑜𝑠𝑣)3


−𝜋/2 ≤ 𝑢 ≤ 𝜋/2 𝑦 = (𝑏 𝑠𝑖𝑛𝑢 𝑐𝑜𝑠𝑣)3
−𝜋 ≤ 𝑣 ≤ 𝜋 𝑧 = (𝑐 𝑠𝑖𝑛𝑣 )3
BIRLA VISHVAKARMA MAHAVIDYALAYA
VALLABHVIDYANAGAR
ES106: Programming for Engineers

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.

There are three popular sorting algorithms

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:

Objective: To understand different searching techniques using MATLAB.

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

Root of Equation with single variable


Experiment No: 12
Date:

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:

 In numerical analysis, Newton–Raphson method (also known as the Newton’s method),


named after Isaac Newton and Joseph Raphson, is a method for finding successively
better approximations to the roots (or zeroes) of a real-valued function.
 The Newton–Raphson method in one variable is implemented as follows:
 Given a function 𝑓 defined over the reals 𝑥, and its derivative 𝑓’, we begin with a first
guess 𝑥0 for a root of the function 𝑓. Provided the function satisfies all the assumptions
made in the derivation of the formula, a better approximation 𝑥1 is

𝑓(𝑥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:

 A potential problem in implementing the Newton-Raphson method is the evaluation of


the derivative. Although this is not inconvenient for polynomials and many other
functions, there are certain functions whose derivatives may be extremely difficult or
inconvenient to evaluate. For these cases, the derivative can be approximated by a
backward finite divided difference,

𝑓(𝑥𝑖−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.

Sr. Equation Interval


No.
a. 𝑥 − log10 𝑥 − 2 = 0 [1,2]

b. 𝑥 log10 𝑥 = 1.2 [2.74,2.75]


𝜋
c. 2𝑥 − 3 sin 𝑥 − 5 = 0 [ , 𝜋]
2
d. 𝑥 − 𝑒 −𝑥 = 0 [0,1]

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.

Sr. Equation Initial Guess for Initial Guesses


No. Newton-Rapson for Secant
method method
a. 𝑥 − log10 𝑥 − 2 = 0 2 [1,2]

b. 𝑥 log10 𝑥 = 1.2 2.75 [2.75,2.78]


𝜋
c. 2𝑥 − 3 sin 𝑥 − 5 = 0 𝜋 [ , 𝜋]
2
d. 𝑥 − 𝑒 −𝑥 = 0 1 [0,1]

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:

Objective: To introduce interpolation polynomial.


Theory:

 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.

Polynomial curve fitting


Syntax

>>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

>> x=[2 4 5];


>> y=[0.5 0.25 0.2];
>> p=polyfit(x,y,2)
p =
0.0250 -0.2750 0.9500
>>polyval(p,1.5)
ans =
0.5937

The lagrange Function


Syntax

>>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

You might also like