[go: up one dir, main page]

0% found this document useful (0 votes)
40 views49 pages

Computational Engineering LAB Manual V8

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 49

Computational Engineering

LAB
Laboratory Manual

(B.Tech. Mechanical Engineering)


School of Technology
Pandit Deendayal Energy University
Gandhinagar
Gujarat
INDEX
MATLAB MODULE
Experiment 1: Introduction to MATLAB & MATLAB basics
Experiment 2: Matrices, Basic Graphics, M-Files
Experiment 3: Data Files, Directories, Text Strings, Arrays
Experiment 4: Multidimensional Arrays, Cell Arrays, Structures
Experiment 5: Programming with MATLAB
Experiment 6: User defined functions and function files
Experiment 7: Electric circuits, Control system
Experiment 8: Different Toolbox of MATLAB
Experiment 9: Engineering Mechanics with MATLAB
Experiment 10: Numerical Methods with MATLAB
Experiment 11: Numerical Integration with MATLAB
Experiment 12: Solving Differential Equations with MATLAB
Experiment 13: Introduction to MATLAB Simulink
Experiment 1: Introduction to MATLAB & MATLAB basics

Objective: To understand basics of MATLAB software.

Theory: MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-


paradigm programming language and numeric computing environment developed by
MathWorks. MATLAB allows matrix manipulations, plotting of functions and data,
implementation of algorithms, creation of user interfaces, and interfacing with programs
written in other languages.
Uses of MATLAB software −

• Dealing with Matrices and Arrays


• 2-D and 3-D Plotting and graphics
• Linear Algebra
• Algebraic Equations
• Non-linear Functions
• Statistics
• Data Analysis
• Calculus and Differential Equations
• Numerical Calculations
• Integration
• Transforms
• Curve Fitting
• Various other special functions
Application of MATLAB
MATLAB is widely used as a computational tool in science and engineering
encompassing the fields of all engineering streams−

• Signal Processing and Communications


• Image and Video Processing
• Control Systems
• Test and Measurement
• Computational fluid dynamics
• Computational Biology, finance
• Solid mechanics, Finite element method

When you start MATLAB®, the desktop appears in its default layout.
The desktop includes these panels:
• Current Folder — Access your files.
• Command Window — Enter commands at the command line, indicated by the
prompt (>>).
• Workspace — Explore data that you create or import from files.
As you work in MATLAB, you issue commands that create variables and call functions.
For example, create a variable named a by typing this statement at the command line:
a=1
MATLAB adds variable a to the workspace and displays the result in the Command
Window.
a=

1
Create a few more variables.
b=2
b=

2
c=a+b
c=

3
d = cos(a)
d=
0.5403
Note that the argument in the trigonometric functions should be in radians !!
Example – sin(45 degree) must be converted to→ sin (45*pi/180 radians).
When you do not specify an output variable, MATLAB uses the variable ans, short
for answer, to store the results of your calculation.
sin(a)
ans =

0.8415
If you end a statement with a semicolon, MATLAB performs the computation, but
suppresses the display of output in the Command Window.
e = a*b;
You can recall previous commands by pressing the up- and down-arrow keys, ↑ and ↓.
Press the arrow keys either at an empty command line or after you type the first few
characters of a command. For example, to recall the command b = 2, type b, and then
press the up-arrow key.
clc- Clear Command
Syntax clc
Description - clc clears all the text from the Command Window, resulting in a clear
screen.
clear - Remove items from workspace, freeing up system memory.
clear removes all variables from the current workspace, releasing them from system
memory.

close - Close one or more figure.


Syntax - close
close(fig), close all
Description - close - closes the current figure.

Commonly used Operators and Special Characters

MATLAB supports the following commonly used operators and special characters −

Operator Purpose

+ Plus; addition operator.

- Minus; subtraction operator.


* Scalar and matrix multiplication operator.

.* Array multiplication operator.

^ Scalar and matrix exponentiation operator.

.^ Array exponentiation operator.

\ Left-division operator.

/ Right-division operator.

.\ Array left-division operator.

./ Array right-division operator.

: Colon; generates regularly spaced elements and represents an


entire row or column.

() Parentheses; encloses function arguments and array indices;


overrides precedence.

[] Brackets; enclosures array elements.

. Decimal point.

… Ellipsis; line-continuation operator

, Comma; separates statements and elements in a row

; Semicolon; separates columns and suppresses display.

% Percent sign; designates a comment and specifies formatting.

_ Quote sign and transpose operator.

._ Nonconjugated transpose operator.

= Assignment operator.

Special Variables and Constants

MATLAB supports the following special variables and constants −

Name Meaning

ans Most recent answer.

eps Accuracy of floating-point precision.


i,j The imaginary unit √-1.

Inf Infinity.

NaN Undefined numerical result (not a number).

pi The number π

Problems to do in MATLAB:
Q. Using MATLAB find the value of Y at (x,t) = (2,2)
𝑌(𝑥, 𝑡) = 𝑒 2𝑡 sin(𝑘𝑥 + 𝜔𝑡) , where k = 4, 𝜔= 1.5 in appropriate units.
Q. Write the complex number 8+5i and its conjugate using MATLAB.
Experiment 2: Matrices, Basic Graphics, M-Files

Objective: To construct Matrices and basic plotting in MATLAB. Also understand the M-
file or the script file in MATLAB.

Theory: A matrix is a two-dimensional array.

Array Creation
To create an array with four elements in a single row, separate the elements with either
a comma (,) or a space.
a = [1 2 3 4]
a = 1×4

1 2 3 4

This type of array is a row vector.


To create a matrix that has multiple rows, separate the rows with semicolons.
a = [1 3 5; 2 4 6; 7 8 10]
a = 3×3

1 3 5
2 4 6
7 8 10

Another way to create a matrix is to use a function, such as ones, zeros, or rand. For
example, create a 5-by-1 column vector of zeros.
z = zeros(5,1)
z = 5×1

0
0
0
0
0

Matrix and Array Operations


MATLAB allows you to process all of the values in a matrix using a single arithmetic
operator or function.
a + 10
ans = 3×3

11 13 15
12 14 16
17 18 20

sin(a)
ans = 3×3

0.8415 0.1411 -0.9589


0.9093 -0.7568 -0.2794
0.6570 0.9894 -0.5440

To transpose a matrix, use a single quote ('):


a'
ans = 3×3

1 2 7
3 4 8
5 6 10

inv

Matrix inverse
Syntax
Y = inv(X)
Description
Y = inv(X) computes the inverse of square matrix X.
• X^(-1) is equivalent to inv(X).
• x = A\b is computed differently than x = inv(A)*b and is recommended for
solving systems of linear equations.
Examples
Inverse Matrix
Compute the inverse of a 3-by-3 matrix.
X = [1 0 2; -1 5 0; 0 3 -9]
X = 3×3

1 0 2
-1 5 0
0 3 -9

Y = inv(X)
Y = 3×3

0.8824 -0.1176 0.1961


0.1765 0.1765 0.0392
0.0588 0.0588 -0.0980
eig

Eigenvalues and eigenvectors


Syntax
e = eig(A)
[V,D] = eig(A)
[V,D] = eig(A,B)
Description
e = eig(A) returns a column vector containing the eigenvalues of square matrix A.
[V,D] = eig(A) returns diagonal matrix D of eigenvalues and matrix V whose columns are
the corresponding right eigenvectors, so that A*V = V*D.

The matrix operators for multiplication, division, and power each have a corresponding
array operator that operates element-wise. For example, raise each element of a to the
third power:
a.^3
ans = 3×3

1 27 125
8 64 216
343 512 1000

Concatenation
Concatenation is the process of joining arrays to make larger ones. In fact, you made
your first array by concatenating its individual elements. The pair of square
brackets [] is the concatenation operator.
A = [a,a]
A = 3×6

1 3 5 1 3 5
2 4 6 2 4 6
7 8 10 7 8 10
Concatenating arrays next to one another using commas is
called horizontal concatenation. Each array must have the same number of rows.
Similarly, when the arrays have the same number of columns, you can
concatenate vertically using semicolons.
A = [a; a]
A = 6×3

1 3 5
2 4 6
7 8 10
1 3 5
2 4 6
7 8 10

To plot the graph of a function, you need to take the following steps −
• Define x, by specifying the range of values for the variable x, for which the
function is to be plotted
• Define the function, y = f(x)
• Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y =
x for the range of values for x from 0 to 100, with an increment of 5.
Create a script file and type the following code −

x = [0:5:100];
y = x;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Let us take one more example to plot the function y = x2. In this example, we will draw
two graphs with the same function, but in second time, we will reduce the value of
increment. Please note that as we decrease the increment, the graph becomes smoother.
Create a script file and type the following code −

x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x.^2;
plot(x, y)
When you run the file, MATLAB displays the following plot −

Change the code file a little, reduce the increment to 5 −

x = [-100:5:100];
y = x.^2;
plot(x, y)
MATLAB draws a smoother graph −

Adding Title, Labels, Grid Lines and Scaling on the Graph


MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to
adjust the axes to spruce up the graph.
• The xlabel and ylabel commands generate labels along x-axis and y-axis.
• The title command allows you to put a title on the graph.
• The grid on command allows you to put the grid lines on the graph.
• The axis equal command allows generating the plot with the same scale factors
and the spaces on both axes.
• The axis square command generates a square plot.

Example

Create a script file and type the following code −

x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
MATLAB generates the following graph −

Drawing Multiple Functions on the Same Graph

You can draw multiple graphs on the same plot. The following example demonstrates
the concept −

Example

Create a script file and type the following code −

x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')
MATLAB generates the following graph −

2-D and 3-D Plots


Line Plots
To create two-dimensional line plots, use the plot function. For example, plot the sine
function over a linearly spaced vector of values from 0 to 2π:
x = linspace(0,2*pi);
y = sin(x);
plot(x,y)

You can label the axes and add a title.


xlabel("x")
ylabel("sin(x)")
title("Plot of the Sine Function")
By adding a third input argument to the plot function, you can plot the same variables
using a red dashed line.
plot(x,y,"r--")

"r--" is a line specification. Each specification can include characters for the line color,
style, and marker. A marker is a symbol that appears at each plotted data point, such as
a +, o, or *. For example, "g:*" requests a dotted green line with * markers.
Notice that the titles and labels that you defined for the first plot are no longer in the
current figure window. By default, MATLAB® clears the figure each time you call a
plotting function, resetting the axes and other elements to prepare the new plot.
To add plots to an existing figure, use hold on. Until you use hold off or close the window,
all plots appear in the current figure window.
x = linspace(0,2*pi);
y = sin(x);
plot(x,y)

hold on

y2 = cos(x);
plot(x,y2,":")
legend("sin","cos")

hold off

3-D Plots
Three-dimensional plots typically display a surface defined by a function in two
variables, z=f(x,y). For instance, calculate z=xe−x2−y2 given row and column
vectors x and y with 20 points each in the range [-2,2].
x = linspace(-2,2,20);
y = x';
z = x .* exp(-x.^2 - y.^2);
Then, create a surface plot as - surf(x,y,z)
Both the surf function and its companion mesh display surfaces in three
dimensions. surf displays both the connecting lines and the faces of the surface in
color. mesh produces wireframe surfaces that color only the connecting lines.

The M Files

MATLAB allows writing two kinds of program files −


• Scripts − script files are program files with .m extension. In these files, you write
series of commands, which you want to execute together. Scripts do not accept
inputs and do not return any outputs. They operate on data in the workspace.
• Functions − functions files are also program files with .m extension. Functions
can accept inputs and return outputs. Internal variables are local to the function.
You can use the MATLAB editor or any other text editor to create your .mfiles. In this
section, we will discuss the script files. A script file contains multiple sequential lines of
MATLAB commands and function calls. You can run a script by typing its name at the
command line.

Creating and Running Script File

To create scripts files, you need to use a text editor. You can open the MATLAB editor in
two ways −

• Using the command prompt


• Using the IDE
If you are using the command prompt, type edit in the command prompt. This will open
the editor. You can directly type edit and then the filename (with .m extension)

Questions to do in MATLAB:
1 2 3
1. Define a matrix as A = (2 3 4)
1 2 5
Find the transpose and inverse of this matrix using MATLAB.

2. Draw the functions


𝑦1 = 𝑥 2
𝑦2 = 𝑥 3
𝑦3 = 𝑒 𝑥
𝑦4 = sin(𝑥) ∗ cos (𝑥)

on same plot for the range of x from -5 to +5.


Experiment 3: Data Files, Directories, Text Strings, Arrays

Aim: To import data files and make directories, strings and arrays using MATLAB.

Theory: importdata
Load data from file
Syntax
A = importdata(filename)

Description
A = importdata(filename) loads data into array A.

Import and Display an Image


Try This ExampleCopy Command Copy Code
Import and display the sample image, ngc6543a.jpg.
A = importdata('ngc6543a.jpg');
image(A)

Import a Text File and Return Detected Delimiter


Using a text editor, create a comma-delimited ASCII file called myfile02.txt.
1,2,3
4,5,6
7,8,9
Import the file, and display the output data and detected delimiter character.
filename = 'myfile02.txt';
[A,delimiterOut]=importdata(filename)
A=

1 2 3
4 5 6
7 8 9

delimiterOut =

,
you can read spreadsheet data into a table using the readtable function with the file name, for
example:
T = readtable('patients.xls');
You can also select the range of data to import by specifying the range parameter. For example,
read the first five rows and columns of the spreadsheet. Specify the range in Excel notation
as 'A1:E5'.
T = readtable('patients.xls','Range','A1:E5')
T=

4×5 table

LastName Gender Age Location Height


____________ __________ ___ _____________________________ ______

{'Smith' } {'Male' } 38 {'County General Hospital' } 71


{'Johnson' } {'Male' } 43 {'VA Hospital' } 69
{'Williams'} {'Female'} 38 {'St. Mary's Medical Center'} 64
{'Jones' } {'Female'} 40 {'VA Hospital' } 67

dir

List folder contents


Syntax
dir
dir name

Description
dir lists files and folders in the current folder.
dir name lists files and folders that match name. When name is a folder, dir lists the contents of
the folder. Specify name using absolute or relative path names. The name argument can include
the * wildcard in the file name, and both the * and the ** wildcard in the path name. Characters
next to a ** wildcard must be file separators.
listing = dir(name) returns attributes about name.

Problems to do in MATLAB –
Q. Refer to the attached NACA0012 airfoil profile data downloaded from link -
http://airfoiltools.com/plotter/index
Import the data in MATLAB using "importdata" command. Once you import the data
you notice that the imported data is of structure type (it constitutes several fields). Take
the points data as input and do the "scatter plot" in MALTAB. (you will notice that the
scatter plot appears to be actual NACA0012 airfoil profile). Submit the MATLAB code .m
file with filename as - name_rollno_exp3
Airfoil data is as follows –
Airfoil surface
X(mm) Y(mm)
100 0.12
95 1.027
90 1.867
80 3.32
70 4.48
60 5.32
50 5.827
40 6
30 5.8
20 5.093
15 4.493
10 3.653
7.5 3.133
5 2.493
2.5 1.68
1.25 1.133
0 0
1.25 -1.133
2.5 -1.68
5 -2.493
7.5 -3.133
10 -3.653
15 -4.493
20 -5.093
30 -5.8
40 -6
50 -5.827
60 -5.32
70 -4.48
80 -3.32
90 -1.867
95 -1.027
100 -0.12
Experiment No. 4 - Multidimensional Arrays, Cell Arrays, Structures

Objective: To construct multidimensional arrays and structures in MATLAB.

Arrays in MATLAB

In this section, we will discuss some functions that create some special arrays. For all these
functions, a single argument creates a square array, double arguments create rectangular array.
The zeros() function creates an array of all zeros −
For example −

zeros(5)
MATLAB will execute the above statement and return the following result −
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
The ones() function creates an array of all ones −
For example −

ones(4,3)
MATLAB will execute the above statement and return the following result −
ans =
1 1 1
1 1 1
1 1 1
1 1 1
The eye() function creates an identity matrix.
For example −

eye(4)
MATLAB will execute the above statement and return the following result −
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
The rand() function creates an array of uniformly distributed random numbers on (0,1) −
For example −
rand(3, 5)
MATLAB will execute the above statement and return the following result −
ans =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003

A Magic Square

A magic square is a square that produces the same sum, when its elements are added row-wise,
column-wise or diagonally.
The magic() function creates a magic square array. It takes a singular argument that gives the
size of the square. The argument must be a scalar greater than or equal to 3.

magic(4)
MATLAB will execute the above statement and return the following result −
ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

Multidimensional Arrays

An array having more than two dimensions is called a multidimensional array in MATLAB.
Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix.
Generally to generate a multidimensional array, we first create a two-dimensional array and
extend it.
For example, let's create a two-dimensional array a.

a = [7 9 5; 6 1 9; 4 3 2]
MATLAB will execute the above statement and return the following result −
a=
7 9 5
6 1 9
4 3 2
The array a is a 3-by-3 array; we can add a third dimension to a, by providing the values like −

a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]
MATLAB will execute the above statement and return the following result −
a=

ans(:,:,1) =

0 0 0
0 0 0
0 0 0
ans(:,:,2) =

1 2 3
4 5 6
7 8 9
We can also create multidimensional arrays using the ones(), zeros() or the rand() functions.
For example,

b = rand(4,3,2)
MATLAB will execute the above statement and return the following result −
b(:,:,1) =
0.0344 0.7952 0.6463
0.4387 0.1869 0.7094
0.3816 0.4898 0.7547
0.7655 0.4456 0.2760

b(:,:,2) =
0.6797 0.4984 0.2238
0.6551 0.9597 0.7513
0.1626 0.3404 0.2551
0.1190 0.5853 0.5060
We can also use the cat() function to build multidimensional arrays. It concatenates a list of
arrays along a specified dimension −
Syntax for the cat() function is −

B = cat(dim, A1, A2...)


Where,
• B is the new array created
• A1, A2, ... are the arrays to be concatenated
• dim is the dimension along which to concatenate the arrays

Example

Create a script file and type the following code into it −

a = [9 8 7; 6 5 4; 3 2 1];
b = [1 2 3; 4 5 6; 7 8 9];
c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])
When you run the file, it displays −
c(:,:,1) =
9 8 7
6 5 4
3 2 1
c(:,:,2) =
1 2 3
4 5 6
7 8 9
c(:,:,3) =
2 3 1
4 7 8
3 9 0

Array Functions

MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array
contents.

Function Purpose

length Length of vector or largest array dimension

ndims Number of array dimensions

numel Number of array elements

size Array dimensions

iscolumn Determines whether input is column vector

isempty Determines whether array is empty

ismatrix Determines whether input is matrix

isrow Determines whether input is row vector

isscalar Determines whether input is scalar

isvector Determines whether input is vector

blkdiag Constructs block diagonal matrix from input arguments

circshift Shifts array circularly

ctranspose Complex conjugate transpose

diag Diagonal matrices and diagonals of matrix

flip Flips array

fliplr Flips matrix from left to right

flipud Flips matrix up to down

repmat Replicates and tile array

reshape Reshapes array

rot90 Rotates matrix 90 degrees

shiftdim Shifts dimensions


issorted Determines whether set elements are in sorted order

sort Sorts array elements in ascending or descending order

sortrows Sorts rows in ascending order

transpose Transpose

Examples

The following examples illustrate some of the functions mentioned above.


Length, Dimension and Number of elements −
Create a script file and type the following code into it −

x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];


length(x) % length of x vector
y = rand(3, 4, 5, 2);
ndims(y) % no of dimensions in array y
s = ['Ravi', 'Eesha', 'Shantanu', 'Shilpi', 'Manisha'];
numel(s) % no of elements in s
When you run the file, it displays the following result −
ans = 8
ans = 4
ans = 23

Cell Array
Arrays that can contain data of varying types and sizes

A cell array is a data type with indexed data containers called cells, where each cell can contain any type
of data. For instance,
c = {42, rand(5), "abcd"}
returns
c=
1×3 cell array
{[42]} {5×5 double} {["abcd"]}
To access the contents of a cell, enclose indices in curly braces, such as c{1} to return 42 and c{3} to
return "abcd". For more information, see Access Data in Cell Array.

Structures

Arrays with named fields that can contain data of varying types and sizes
A structure array is a data type that groups related data using data containers called fields. Each
field can contain any type of data. Access data in a structure using dot notation of the
form structName.fieldName
struct

Structure array
Description
A structure array is a data type that groups related data using data containers called fields. Each
field can contain any type of data. Access data in a field using dot notation of the
form structName.fieldName.
Creation
When you have data to put into a new structure, create the structure using dot notation to name
its fields one at a time:
s.a = 1;
s.b = {'A','B','C'}
s = struct with fields:
a: 1
b: {'A' 'B' 'C'}

Field names can contain ASCII letters (A–Z, a–z), digits (0–9), and underscores, and must begin
with a letter. The maximum length of a field name is namelengthmax.
You also can create a structure array using the struct function, described below. You can specify
many fields simultaneously, or create a nonscalar structure array.
Syntax
s = struct
Create a structure by adding fields to it using dot notation. The fields contain x- and y-values for
a sine wave, and text that describes the data.
data.x = linspace(0,2*pi);
data.y = sin(data.x);
data.title = 'y = sin(x)'
data = struct with fields:
x: [0 0.0635 0.1269 0.1904 0.2539 0.3173 0.3808 0.4443 0.5077 ... ]
y: [0 0.0634 0.1266 0.1893 0.2511 0.3120 0.3717 0.4298 0.4862 ... ]
title: 'y = sin(x)'

Plot the sine wave. You can refer to the arrays of x- and y-values by their field names. Then add
the title.
plot(data.x,data.y)
title(data.title)
Problems to do in MATLAB –
Q. Using “fields of structure”, plot following on same figure
𝑦1 = 𝑥 2
𝑦2 = 𝑥 3
𝑦3 = 𝑒 𝑥
𝑦4 = sin(𝑥) ∗ cos⁡
(𝑥)
Experiment No. 5 - Programming with MATLAB

Objective: To create a program in MATLAB using FOR loop, WHILE loops and if-else
commands.

for

for loop to repeat specified number of times


Syntax
for index = values
statement
end
Description
for index = values, statements, end executes a group of statements in a loop for a specified
number of times. values has one of the following forms:
• initVal:endVal — Increment the index variable from initVal to endVal by 1, and repeat
execution of statements until index is greater than endVal.
• initVal:step:endVal — Increment index by the value step on each iteration, or
decrements index when step is negative.
Example – Create an identity matrix using FOR loop command.
A = zeros(4,4);
for i = 1:4
A(i,i) = 1;
end

while

while loop to repeat when condition is true


Syntax
while expression
statements
end
Description
while expression, statements, end evaluates an expression, and repeats the execution of a group
of statements in a loop while the expression is true. An expression is true when its result is
nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the
expression is false.

Example - Use a while loop to calculate factorial(10).


n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])
n! = 3628800

if, elseif, else

Execute statements if condition is true


Syntax
if expression
statements
elseif expression
statements
else
statements
end
Description
if expression, statements, end evaluates an expression, and executes a group of statements when
the expression is true. An expression is true when its result is nonempty and contains only
nonzero elements (logical or real numeric). Otherwise, the expression is false.
The elseif and else blocks are optional. The statements execute only if previous expressions in
the if...end block are false. An if block can include multiple elseif blocks.
Examples
Use if, elseif, and else for Conditional Assignment

Create a tridiagonal matrix using if else assignment.


First create a matrix of 1s.
nrows = 4;
ncols = 6;
A = ones(nrows,ncols);
Loop through the matrix and assign each element a new value. Assign 2 on the main diagonal, -
1 on the adjacent diagonals, and 0 everywhere else.
for c = 1:ncols
for r = 1:nrows

if r == c
A(r,c) = 2;
elseif abs(r-c) == 1
A(r,c) = -1;
else
A(r,c) = 0;
end

end
end
A
A = 4×6

2 -1 0 0 0 0
-1 2 -1 0 0 0
0 -1 2 -1 0 0
0 0 -1 2 -1 0

Problems to do in MATLAB –
Q. 1.Make a MATLAB program that sums number from 1 to 100 using FOR loop
statement.
2. Make a MATLAB program that sums number from 1 to 100 using While loop
statement,
and submit the single MATLAB code .m file with filename as - name_rollno_exp5
Experiment No. 6 - User defined functions and function files

Objective: To create user defined function in MATLAB.

function

function [y1,...,yN] = myfun(x1,...,xM)


Description
function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts
inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first
executable line of the function. Valid function names begin with an alphabetic character, and can
contain letters, numbers, or underscores.
You can save your function:
• In a function file which contains only function definitions. The name of the file must
match the name of the first function in the file.
• In a script file which contains commands and function definitions. Functions must be at
the end of the file. Script files cannot have the same name as a function in the file.
Functions are supported in scripts in R2016b or later.

Examples
Function with One Output
Define a function in a file named average.m that accepts an input vector, calculates the average
of the values, and returns a single result.
function ave = average(x)
ave = sum(x(:))/numel(x);
end
Call the function from the command line.
z = 1:99;
ave = average(z)
ave =
50
Function with Multiple Outputs
Define a function in a file named stat.m that returns the mean and standard deviation of an
input vector.
function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end
Call the function from the command line.
values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat(values)
ave =
47.3400
stdev =
29.4124

Multiple Functions in a File

Define two functions in a file named stat2.m, where the first function calls the second.

function [m,s] = stat2(x)


n = length(x);
m = avg(x,n);
s = sqrt(sum((x-m).^2/n));
end
function m = avg(x,n)
m = sum(x)/n;
end

Call the function from the command line.


z = 1:99;
>> [mymean, mystd] = stat2(z)

mymean =

50

mystd =

28.5774

Problems to do in MATLAB –
Q. Make a function file that calculates mean median and mode of any given five
numbers. And submit the MATLAB code .m file with filename as -
name_rollno_exp6
Experiment No. 7 - Electric circuits and Control systems

Objective: For a given electrical circuit, construct a control systems model and obtain
its step/impulse responses.

Consider the electrical LRC circuit shown in Figure below.

The circuit consists of an inductance L = 1 (henry), a resistance R = 10 (ohm), and a capacitance


C = 510*10^-6 (farad). Applying Kirchhoff’s voltage law to the system, we obtain the following
equations:

If ei is assumed to be the input voltage of 1.53 volts and eo the output, then the transfer function
G(s) of this system is found to be,

MATLAB script for evaluating the step response -


R = 10; % resistor resistance
L = 1; % inductor inductance
C = 510*10^-6; % capacitor capacitance
ei = 1.53; % battery voltage
num = 1;
den = [L*C,R*C,1];
sys = tf(num,den) ; % model transfer function
figure(1);
step(sys*ei)

Problems to do in MATLAB –
Q. Consider the electrical circuit as given below – Find the transfer function and its step
response.

Where, R1 = 10;
R2 = 5 ,
C1 = 210*10^-5;
C2 = 510*10^-6;
and ei = 1.53; in appropriate units.
Experiment No: 8 - Different Toolboxes of MATLAB
Objective: To understand various toolbox associated with MATLAB

MATLAB Add-On Toolboxes


• Statistics and Machine Learning Toolbox™ (Statistics and Machine Learning Toolbox)
• Curve Fitting Toolbox™ (Curve Fitting Toolbox)
• Control System Toolbox™ (Control System Toolbox)
• Signal Processing Toolbox™ (Signal Processing Toolbox)
• Mapping Toolbox™ (Mapping Toolbox)
• System Identification Toolbox™ (System Identification Toolbox)
• Deep Learning Toolbox™ (Deep Learning Toolbox)
• DSP System Toolbox™ (DSP System Toolbox)
• Datafeed Toolbox™ (Datafeed Toolbox)
• Financial Toolbox™ (Financial Toolbox)
• Image Processing Toolbox™ (Image Processing Toolbox)
• Text Analytics Toolbox™ (Text Analytics Toolbox)
• Predictive Maintenance Toolbox™
Tutorial for Curve Fitting Toolbox ™

Introducing the Curve Fitting App


You can fit curves and surfaces to data and view plots with the Curve Fitting app.
• Create, plot, and compare multiple fits.
• Use linear or nonlinear regression, interpolation, smoothing, and custom equations.
• View goodness-of-fit statistics, display confidence intervals and residuals, remove outliers, and
assess fits with validation data.
• Automatically generate code to fit and plot curves and surfaces, or export fits to the workspace
for further analysis.
Fit a Curve
1. Load some example data at the MATLAB command line:
®

load census.mat
2. Open the Curve Fitting app by entering:
cftool

Alternatively, click Curve Fitting on the Apps tab.


3. Select X data and Y data. For details, see Selecting Data to Fit in Curve Fitting App.

The Curve Fitting app creates a default polynomial fit to the data.
4. Try different fit options. For example, change the polynomial Degree to 3 to fit a cubic
polynomial.

5. Select a different model type from the fit category list, e.g., Smoothing Spline. For
information about models you can fit, see Model Types for Curves and Surfaces.

Problems to do in MATLAB-
Q. Suppose we have xdata and ydata points observed in any experiment as follows –
xdata 0.32 0.78 0.47 0.04 0.18 0.72 0.47 0.15 0.34 0.61 0.19 0.74 0.24 0.92 0.27
ydata 0.68 0.55 0.43 0.64 0.65 0.68 0.64 0.95 0.21 0.71 0.24 0.12 0.61 0.45 0.46

Using curve fitting toolbox, assess the goodness of fits with (a) polynomial fit with 5th
degree (b) smooth spline?
Experiment No. 9 - Engineering Mechanics with MATLAB

Objective: To obtain the governing equation of simple spring mass damper system and
simulate its step response in MATLAB.
Consider the mechanical system as given below – Find the transfer function and its step
response.

Where, m = 1 kg, k = 1 N/m.

Applying Newton’s law of motion,

∑ 𝐹𝑒𝑥𝑡𝑒𝑟𝑛𝑎𝑙 = 𝑚𝑎

𝑑𝑥 𝑑2 𝑥
𝐹 − 𝑘𝑥 − 𝑏 =𝑚 2
𝑑𝑡 𝑑𝑡
Taking Laplace transform of governing equation,
(𝑚𝑠 2 + 𝑏𝑠 + 𝑘)𝑋(𝑠) = 𝐹(𝑠)
Transfer function of the plant is,
𝑋(𝑠) 1
𝐺(𝑠) = = 2
𝐹(𝑠) 𝑚𝑠 + 𝑏𝑠 + 𝑘
Using parameters, m = 1kg, b = 2 Ns/m, k = 20 N/m, F = 1N, plot the step response of
the system.
In MATLAB,
m = 1; % mass of block
b = 2; % damping coefficient of damper
k = 20; % spring constant
F = 1; % input force
num = 1;
den = [m,b,k];
sys = tf(num,den) ; % model transfer function
figure(1);
step(sys*F)

Application – Car shock-absorber system can be modelled as spring mass system.

Q. Problems to do in MATLAB-
An automobile suspension system can be modelled as shown below, where xi is
the input from ground bump and xo is the response of the car body. First obtain
the governing equation and transfer function of the plant using xi displacement
as input and xo displacement as output. Using MATLAB find the step response of
the system. Given parameters, m = 1000kg, b = 2000 Ns/m, k = 20000 N/m
Experiment 10: Numerical Methods with MATLAB

Objective: Numerically solve the 2D heat conduction equation for flat plate using explicit
method via MATLAB.
Theory - Consider a 2D metal plate with dimensions 0.75x0.75 m2 is kept at 100 degree
C at one of it end and rest of the ends are initially at 0 degree C as shown in the figure.
The transient Fourier law of heat conduction for 2D metal plate is given by,

𝜕𝑇 𝜕 2𝑇 𝜕 2𝑇
= 𝑘 ( 2 + 2)
𝜕𝑡 𝜕𝑥 𝜕𝑦

Where T(x,y,t) is the temperature at any location and time and x, y, t are space and time
coordinates. Assume the thermal conductivity of plate is K = 1 W/m degree C.

Take the spatial discretization as delta x = delta y = 0.025 m.


Using explicit finite difference method, the discrete equation can be obtained using
Taylor series expansion as below,
𝑛+1 𝑛 𝑛 𝑛 𝑛 𝑛 𝑛 𝑛
𝑇𝑖,𝑗 − 𝑇𝑖,𝑗 𝑇𝑖+1,𝑗 − 2𝑇𝑖,𝑗 + 𝑇𝑖−1,𝑗 𝑇𝑖,𝑗+1 − 2𝑇𝑖,𝑗 + 𝑇𝑖,𝑗−1
= 𝑘( + )
∆𝑡 ∆𝑥 2 ∆𝑦 2

Suppose ∆𝑥 = ∆𝑦 = ∆ℎ

𝑛+1 𝑛 𝑘∆𝑡 𝑛 𝑛 𝑛 𝑛 𝑛 𝑛
𝑇𝑖,𝑗 = 𝑇𝑖,𝑗 + 2
(𝑇𝑖+1,𝑗 − 2𝑇𝑖,𝑗 + 𝑇𝑖−1,𝑗 + 𝑇𝑖,𝑗+1 − 2𝑇𝑖,𝑗 + 𝑇𝑖,𝑗−1 )
∆ℎ
Take the spatial discretization as ∆𝑥 = ∆𝑦 = ∆ℎ = 0.025 m and ∆𝑡 =
0.00015, thermal conductivity of plate is K = 1 W/m degree C
MATLAB program-
% Explicit method for 2D heat equation in flat plate
close all; clear all; clc;
L =0.75;
dx = 0.05;
dy=0.05;
N = L/dx +1;
x = linspace(0,dx,N);
y = linspace(0,dy,N);
dt = 0.00015;
epsilon = 1e-4;
T_new = zeros(N,N);

for i=1:N
for j=1:N
T_new(1,j) =100;
T_new(i,1) =1;
T_new(N,j)=1;
T_new(i,N)=1;
end
end
error =1;iter=0;
while(error > epsilon)
iter=iter+1;
T = T_new;
for i=2:N-1
for j =2:N-1
T_new(i,j) = dt*((T(i+1,j)-2*T(i,j)+T(i-1,j))/dx^2 +(T(i,j+1)-2*T(i,j)+T(i,j-1))/dy^2) + T(i,j);
end
end
error = max(max(abs(T-T_new)));

figure(2);
contourf(T_new); shading flat;colorbar;
colorbar;
xlabel('x');ylabel('y')

end

Q. Problems to do in MATLAB-
Consider 1D heat conduction in metal rod as below.

1D heat conduction governing equation is given below,


𝜕𝑇 𝜕 2𝑇
= 𝑘 ( 2)
𝜕𝑡 𝜕𝑥

Write down the discretized equation is explicit finite difference method and obtain the
Temperature profile T(x,t). Take length of rod is 0.75 m, ∆𝑥= 0.025 m, ∆𝑡 =
0.00015, thermal conductivity of plate is K = 1 W/m degree C.
Experiment 11: Numerical Integration with MATLAB
Objective: To do numerical integration using MATLAB commands.
Trapezoidal Method
trapz performs numerical integration via the trapezoidal method. This method approximates the
integration over an interval by breaking the area down into trapezoids with more easily computable
areas. For example, here is a trapezoidal integration of the sine function using eight evenly-spaced
trapezoids:

trapz
Trapezoidal numerical integration

Syntax
Q = trapz(Y)
Q = trapz(X,Y)
Q = trapz(___,dim)
Q = trapz(Y) computes the approximate integral of Y via the trapezoidal method with unit spacing. The
size of Y determines the dimension to integrate along:
• If Y is a vector, then trapz(Y) is the approximate integral of Y.
• If Y is a matrix, then trapz(Y) integrates over each column and returns a row vector of integration
values.
Q = trapz(X,Y) integrates Y with respect to the coordinates or scalar spacing specified by X.
• If X is a vector of coordinates, then length(X) must be equal to the size of the first dimension
of Y whose size does not equal 1.
• If X is a scalar spacing, then trapz(X,Y) is equivalent to X*trapz(Y).
Q = trapz(___,dim) integrates along the dimension dim using any of the previous syntaxes. You must
specify Y, and optionally can specify X. If you specify X, then it can be a scalar or a vector with length equal
to size(Y,dim). For example, if Y is a matrix, then trapz(X,Y,2) integrates each row of Y.
Examples
Integrate Vector of Data with Unit Spacing
Calculate the integral of a vector where the spacing between data points is 1.
Create a numeric vector of data.
Y = [1 4 9 16 25];

Y contains function values for f(x)=x2 in the domain [1, 5].


Use trapz to integrate the data with unit spacing.
Q = trapz(Y)
Q = 42
This approximate integration yields a value of 42. In this case, the exact answer is a little
less, The trapz function overestimates the value of the integral because f(x) is concave up.
Integrate Vector of Data with Nonunit Spacing
Calculate the integral of a vector where the spacing between data points is uniform, but not equal to 1.
Create a domain vector.
X = 0:pi/100:pi;
Calculate the sine of X.
Y = sin(X);
Integrate Y using trapz.
Q = trapz(X,Y)
Q = 1.9998
When the spacing between points is constant, but not equal to 1, an alternative to creating a vector
for X is to specify the scalar spacing value. In that case, trapz(pi/100,Y) is the same as pi/100*trapz(Y).

Q. Problems to do in MATLAB-
Find the area under the curve y = cos(2x) for the range 0 to pi using MALAB trapz
function. Submit your code in .m format.
Experiment 12: Solving Differential Equations with MATLAB
Objective: To solve ordinary differential equations using MATLAB inbuilt command
ode45.

ode45
Solve differential equations —

Syntax
[t,y] = ode45(odefun,tspan,y0)

[t,y] = ode45(odefun,tspan,y0,options)

[t,y,te,ye,ie] = ode45(odefun,tspan,y0,options)

sol = ode45(___)

Description
[t,y] = ode45(odefun,tspan,y0), where tspan = [t0 tf], integrates the system of differential
equations y′=f(t,y) from t0 to tf with initial conditions y0. Each row in the solution
array y corresponds to a value returned in column vector t.
[t,y] = ode45(odefun,tspan,y0,options) also uses the integration settings defined by options,
which is an argument created using the odeset function. For example, use
the AbsTol and RelTol options to specify absolute and relative error tolerances, or the Mass option to
provide a mass matrix.

Example
Solve the ODE

y′=2t.
Specify a time interval of [0 5] and the initial condition y0 = 0.
tspan = [0 5];
y0 = 0;
[t,y] = ode45(@(t,y) 2*t, tspan, y0);
Plot the solution.
plot(t,y,'-o')
Q. Problems to do in MATLAB-

Find the solution y1(t) and y2(t).


Experiment 13: Introduction to MATLAB Simulink
Objective: Understand basics of MATLAB package SIMULINK.

Using Simulink
To open Simulink, type in the MATLAB work space −
simulink
Simulink opens with the Library Browser. The Library Browser is used for building
simulation models.
On the left side window pane, you will find several libraries categorized on the basis of
various systems, clicking on each one will display the design blocks on the right window
pane.
Building Models
To create a new model, click the New button on the Library Browser's toolbar. This
opens a new untitled model window.

A Simulink model is a block diagram.


Model elements are added by selecting the appropriate elements from the Library
Browser and dragging them into the Model window.
Alternately, you can copy the model elements and paste them into the model window.
Examples
Drag and drop items from the Simulink library to make your project.
For the purpose of this example, two blocks will be used for the simulation - A Source (a
signal) and a Sink (a scope). A signal generator (the source) generates an analog signal,
which will then be graphically visualized by the scope(the sink).
Begin by dragging the required blocks from the library to the project window. Then,
connect the blocks together which can be done by dragging connectors from connection
points on one block to those of another.
Let us drag a 'Sine Wave' block into the model.
Select 'Sinks' from the library and drag a 'Scope' block into the model.

Drag a signal line from the output of the Sine Wave block to the input of the Scope block.
Run the simulation by pressing the 'Run' button, keeping all parameters default (you
can change them from the Simulation menu)
You should get the below graph from the scope.

Q. Problems to do in MATLAB-
Using SIMULINK, generate sine wave, square wave, sawtooth wave.

You might also like