You are on page 1of 61

LAB#2:

IMPLEMENTATION OF CONSTANTS,
VARIABLES AND EXPRESSIONS
The learning objectives are:
• Knowledge of MATLAB character set and Data types.
• Study of constants and variables and related useful functions.
• Study of functions used for conversion of Co-ordinate systems.
• Study of arithmetic, relational and logical operators.
• Knowledge of hierarchy of operations and built-in functions.
• Use of assignment statement.

Introduction:
MATLAB is a proprietary multi-paradigm programming language and numerical 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.

Character Set:Character set includes all characters that are legal in BASIC commands,


statements, functions, and variables. The set comprises alphabetic, numeric, and special characters.
The alphabetic characters in BASIC are the uppercase and lowercase letters of the alphabet.

Data Types:

1. Character Data Types:

 Character Data Type


Char strings can contain any printing or non-printing character, and the null character ("\0"). In
uncompressed tables, char strings are stored blank-padded to the declared length. (If the column is
nullable, char columns require an additional byte of storage.) For example, if you enter "ABC" into
a char(5) column, five bytes are stored, as follows:
"ABC"

1|Page
In compressed tables, trailing blanks are removed from char columns. In general, if your
application must preserve trailing blanks, use varchar.
Leading and embedded blanks are significant when comparing char strings (unlike c strings). For
example, the following char strings are different:
"A B C"
"ABC"
When retrieving char strings using the question mark (?) wildcard character, you must include any
trailing blanks you want to match.
 Varchar Data Type
Varchar strings are variable-length strings, stored as a 2-byte (I2) length specifier followed by data.
In uncompressed tables, varchar columns occupy their declared length. (If the column is nullable,
varchar columns require an additional byte of storage.) For example, if you enter "ABC" into a
varchar(5) column, the stored result is:
"03ABCxx"
where "03" is a 2-byte length specifier, "ABC" is three bytes of data, and "xx" represents two bytes
containing unknown (and irrelevant) data.
In compressed tables, varchar columns are stripped of trailing data. For example, if you enter
"ABC" into a varchar(5) column in a compressed table, the stored result is:
"03ABC"
The varchar data type can contain any character, including non-printing characters and the ASCII
null character ("\0").
Blanks are significant in the varchar data type. For example, the following two varchar strings are
not considered equal:
"the store is closed"
 Text Data Type
All ASCII characters except the null character ("\0") are allowed within text strings; null characters
are converted to blanks.
Blanks are not ignored when you compare text strings. Unlike varchar, if the strings are unequal in
length, blanks are not added to the shorter string. For example, assume that you are comparing the
text strings
"abcd"
2. Numeric Data Types:

Numeric data types are in two categories: exact and approximate.


•Exact types include integer and decimal data types.
•Approximate types include floating point data types.

Integer Data Types


Exact numeric data types include the following integer data types:
•tinyint (one-byte)
•smallint (two-byte)
•integer (four-byte)
•bigint (eight-byte)
2|Page
The following table lists the ranges of values for each integer data type:

Decimal Data Type


The decimal data type is an exact numeric data type defined by its precision (total number of digits)
and scale (number of digits to the right of the decimal point). For example:

Specify the decimal data type using the following syntax:


decimal(p,s)
Where:
p
Defines the precision. Minimum is 1; maximum is 39 (38 for X100).
s
Defines the scale. The scale of a decimal value cannot exceed its precision. Scale can be 0 (no
digits to the right of the decimal point).
The following defines a type with precision of 23 decimal digits, 5 of which are after the decimal
point:
decimal(23,5)
Floating Point Data Types
A floating point value is represented either as whole plus fractional digits (like decimal values) or
as a mantissa plus an exponent.
The following is an example of the mantissa and exponent parts of floating point values:

There are two floating point data types:


•float4 (4-byte)
•float (8-byte)
A synonym for float4 is real. Synonyms for float are float8 and double precision.
3|Page
Floating point numbers are stored in four or eight bytes. Internally, eight-byte numbers are rounded
to fifteen decimal digits. The precision of four-byte numbers is processor dependent.
You can specify the minimum required binary precision (number of significant bits) for a floating
point value using the following optional syntax:
float(n)
where n is a value from 0 to 53. Storage is allocated based on the precision that is specified, as
follows:

Constants and Variables:


Constants:

A constant is a data item whose value cannot change during the program’s execution. Thus, as its
name implies – the value is constant.

 Numeric Constants:

Commands Related To Complex Numbers:


Let x is defined as:
Sr. # Operations Description
1 real(x) Give real part of x

2 imag(x) Give imaginary part of x

3 Conj(x) Produce conjugate of x , i.e

4 abs(x) Use to obtain magnitude of complex number

5 angle(x) Use to obtain angle of complex numbers in radians


By default MATLAB accepts and return angle in radians.
4|Page
Conversions of Coordinate System:
Conversion Command
Cartesian To Polar [theta,r]=cart2pol(x,y)
e.g. >>x=1; y=1;
>>[theta,r]=cart2pol(1,1)
>>theta=0.7854 r
=1.4142
Polar To Cartesian [x,y]=pol2cart(theta,r)
e.g. >>theta=1, r=5;
>>[x,y] = pol2cart(1,5)
>>x=2.7015y=4.2074
Character Constant:

A character constant is a character string enclosed in delimiters (apostrophes or quotation marks).


It takes one of the following forms:

[k_]'[ch...]' [C]
[k_]"[ch...]" [C]

k
Is the optional kind parameter: 1 (the default). It must be followed by an underscore ( _ ). Note that
in character constants, the kind must precede the constant.

ch
Is an ASCII character.

A single character constant is one or more characters enclosed in single quotes, such as 'A' , '+'
, or '\n' . In the mikroC PRO for PIC, single-character constants are of the unsigned int type.

Single Character Constant:

String constants, also known as string literals, are a special type of constants which store
fixed sequences of characters. A string literal is a sequence of any number of characters
surrounded by double quotes: "This is a string." The null string, or empty string, is written like

5|Page
String Constants:

Escape Sequence Constants:


Escape Sequence character constants are used in output functions. For example
\b Backspace
\t Tab
\n New line
\r Carriage return
\f Form feed
\\ Print back slash
\’ Print apostrophe
%% Print % or create a cell
Variables:
A variable represents a concept or an item whose magnitude can be represented by a number, i.e.
measured quantitatively. Variables are called variables because they vary,

Special Constants & Variables:


Pi 3.141519
i/j The imaginary unit. √−1

Inf ∞
Ans Default output variables
Built-in Functions:
The functions which are already available in MATLAB are called built-in functions. A complete
list of all MATLAB functions can be seen through Help browser. General Syntax for using these
functions is:
Function_name (expression)
Built-in function Description
exp(x) Calculate
log(x) Calculate Natural logarithm
factorial(x) Calculate Factorial of a number
sin(x) Compute the sine of ‘x’ in radians
cos(x) Cosine; cos(x).

tan(x) Tangent; tan(x)

csc(x) Cosecant; csc(x).

6|Page
sec(x) Secant; sec(x).

cot(x) Cotangent; cot(x).

Sine
Cosine sind(x)
tangant cosd(x)
Cosecant tand(x)
Secant cscd(x)
Cotangant secd(x)
cotd(x)

asin(x) Compute the inverse sine of ‘x’ where ‘x’ must between -1 and 1. The function
returns an angle in radians between and
acos(x) Inverse cosine; arcos x = cos –1 (x).

atan(x) Inverse tangent; arctan x = tan –1 (x).

atan2(y,x) Compute the inverse tangent of value the function returns an angle in radians
that will be between –π and π depending on signs of ‘x’ & ‘y’.
sinh(x) Compute the hyperbolic sine of ’x’ which is equal to
cosh(x) Hyperbolic cosine; cosh(x).

tanh(x) Hyperbolic tangent; sinh(x)/cosh(x).

asinh(x) Compute the inverse hyperbolic sine of ’x’ which is equal to


acosh(x) Inverse hyperbolic cosine; cosh –1 (x)

atanh(x) Inverse hyperbolic tangent; tanh–1 (x).

Element by element operation:


We use element by element operation, when we have expressions in fractional forms.
Operations Operators Algebraic form MATLAB form
Element by element .* ( 4).( 5) Array multiplication
multiplication operator.

Element by element ./ x Array right-division


division y operator.

Element by element .^ x2 Array exponentiation


exponentiation operator.

ILLUSTRATIVE PROGRAMS

Task#1:
Write a program to calculate area of circle having radius 3cm. Area of circle = πr2

7|Page
Program:

>> r=3;
>>areaofcircule=pi*r^2
Output:

areaofcircule =

28.2743

Task#2:
Given two sides a=3.2 and b=4.6 of a triangle and angle theta=600 between these two sides,
find the length of the third side and the area of the triangle.

C = √a2 + b2 − 2abcos(θ)

Area of triangle = absin(θ)


Program:

For side of triangle.


Part 1:

>> a=3.2;
>> b=4.6;
>>theta=60;
>>sideoftriangle = sqrt(a^2+b^2-2*a*b*cosd(theta))
Output:
sideoftriangle = 4.0841
Part 2:
For area of triangle.
>> a=3.2;
>> b=4.6;
>>theta=60;
>>areaoftriangle = 1/2*a*b*sind(60)
Output
Areaoftriangle =6.3739

8|Page
Task#3:
Write a program to convert temperature given in °C say 35.4°C to °F?
°F = °C + 32

Program:

>> C=35.4;
>> F=9/5*C+32

Output:
F=
95.7200

Task#4:
Write MATLAB statements to calculate the sum of the series:

s = 1 − 2x2! + 4x4! − 6x6! + 8x8!forx = 1.5

Program:

>> x=1.5;
>>sum=1-(x^2/factorial(2))+(x^4/factorial(4))-(x^6/factorial(6))+(x^8/factorial(8))

Output:
sum = 0.0708

Task#5:

Express the following number in polar form.


a) 1+2j
9|Page
b) -2+j1
c) (1+2j)(-2+j1)
Program:

Part 1

>> a=1+2j;
>> [theta,r]=cart2pol(real(a),imag(a))

Output:

theta = 1.1071
r = 2.2361
Part 2

>> a=-2+1j;
>> [theta,r]=cart2pol(real(a),imag(a))

Output

theta = 2.6779

r= 2.2361

Task#6:
Evaluate the following assignment statements.

a) q = 2log10x + cosπ + ||y2 − z2|| + √5yz for x=2,y=4,z=3


b) S=(4p+5)(3p+4q-10), for p=3 and q=4
c) Ln(x2 + x + 1) wherex = andx = 1
d) 2
x
wherex = andx =
(x +1)(sinx)

Program:

Part a;

>> x=2;
>> y=4;
>> z=3;
>> 2log10(x) + cosd(pi) + (abs(abs (y^2 - z^2)) + sqrt(5*y*z)
10 | P a g e
Output

ans =

16.3465

Part b:

>> p=3;
>> q=4;
>> S=(4*p+5)*(3*p+4*q-10)

Output:

S= 255
Part 3

When x=1/2;
>> x=1/2;
>>log(x^2+x+1)

Output
ans =

0.5596

When x=1;

>> x=1;
>>log(x^2+x+1)

Output

ans =

1.0986

Part d:

When x=pi/2;

>> x=pi/2;

11 | P a g e
>> s=x^2/(x+1)*(sind(x))

Output
s=

0.0263

When x=pi/4;

>> x=pi/4;
>> s=x^2/(x+1)*(sind(x))

Output
s = 0.0047

Task#7:
Evaluate the given number for ‘x’ from 1 to 2 in steps of 0.1.
y = 1x + x
4
+5x sinx3 sinx

Program:

>> x=[1:0.1:2]';
>> z=(1/x)+((x.^3)/((x.^4)+5.*x.*sind(x)));

Output:

disp(z)
0 0 0 0 0 0 0 0 0 0 0.5612
0 0 0 0 0 0 0 0 0 0 0.5814
0 0 0 0 0 0 0 0 0 0 0.6057
0 0 0 0 0 0 0 0 0 0 0.6344
0 0 0 0 0 0 0 0 0 0 0.6678
0 0 0 0 0 0 0 0 0 0 0.7064
0 0 0 0 0 0 0 0 0 0 0.7505
0 0 0 0 0 0 0 0 0 0 0.8005
0 0 0 0 0 0 0 0 0 0 0.8567
0 0 0 0 0 0 0 0 0 0 0.9195
0 0 0 0 0 0 0 0 0 0 0.9893

Task#8:
Write assignment statements to evaluate the following equations:

12 | P a g e
(A) V olume= πr2hforr = 2, h = 3

>> r=2;

>> h=3;

>>volume=pi*r^2*h

Output

volume =

37.6991

(B) Power = 2π6N0TforN = 1000 , T = 10

program

>> N=1000;

>> T=10;

>>power=2*pi^6*N^0*T

Output

power =

1.9228e+04

(C) Efficiency = V I cos cos θ


2 forV = 250 , I = 5 , R = 2 , coscos θ = 0.8 , ωc= 20
V I cos cosθ+IR+ωc

Program:

>> V=250;
>> I=5;
>> R=2;
>>costheta=0.8;
>> WC=20;
>> s=(V*I*costheta)/(V*I*costheta+I^2*R+WC)

13 | P a g e
Output:

s = 0.9346

Task#9:
For an electrical circuit with an inductance l=0.01mh and resistance r=180 ohms the damped
natural frequency of oscillations is: 1
− RC 2
2 √
Frequency =

LC 4

Write a program to calculate the frequency for different values of ‘c’ varying from 0.1 to 1 in step
of 0.1.

Program:

>> l=0.00001;
>> r=180;
>> c=[0.1:0.1:1]';
>>fre=sqrt((1/(l.*c))-(r.^2/(4.*c.^2)))

Output:

fre =

0 0 0 0 0 0 0 0 0 303.1501

CONCLUSION:

Following lab have been performed on different mathematical operations using matlab with the
help of different commands, variables, trigonometric expressions and Also we have completed
some of our tasks which have been given to us. Although their were some errors occurs while
performing the tasks but they had been cleared. Hoping for gaining more knowledge related to
matlab operations.

LAB#5:
IMPLEMENTATION OF 2-DIMENSIONAL GRAPHS IN MATLAB

14 | P a g e
The learning objectives are:

 To learn the basic features of plotting a graph


 To draw multiple plots using ‘plot’, ‘hold’ and ‘line’ functions
 To learn about different style options to vary color, marker and line-style
 To provide a legend on the plot
 To draw multiple sub-graph windows using subplot functions
 To draw specialized plots such as logarithmic, polar, bar, histogram, pie, stairs and stem
plots
Introduction:

MATLAB provides very good tools for 2-dimensional plots, functions, tools for interactively
creating plots and the ability to export results to many popular graphics formats. It is possible to
customized plots by adding multiple axis, changing line colors and markers, adding annotation
and legends.

Vector data can be visualized with 2-D plotting functions such as line, area, bar and pie charts,
direction and the velocity plots, histograms, polygons and surfaces, scatter or bubble plots and
animations. MATLAB provides functions for visualizing 2-D matrices. In MATLAB, one can
specify plot characteristics, such as viewing angle, perspective, lighting effect, light source,
location and transparency.

List of Commands:
1. General Graphics Command:

Function Syntax Description


Name
plot plot(x , y) To draw a 2-D plot
or
plot(x,y,’style’,’linewidth’,a) Style could be line color, line style or marker
style. ‘a’ is constant for line width in cm let
say 2.
xlabel xlabel(‘string’) To label the x-axis
ylabel ylabel(‘string’) To label the y-axis
title title(‘string’) To give a title to the figure
grid Gridon To show the grid line on the plot

15 | P a g e
text text(‘string’) To write illustrative text on the plot
gtext gtext(‘string’) To place text on the plot using mouse
axis axis(‘equal’) It sets equal scale on axis
axis(‘square’) It sets rectangular frame
axis(‘normal’) It resets to default values
axis(‘off’) It turn off all axis lines, tick-marks and
labels
axis tight It fits the graph in figure window.
Legend legend(‘x’, ‘y’, ‘z’) To produce a boxed legend on the plot
Subplot subplot(r , c , l) To subdivide graphic window into many
or sub-graphs.
subplot rcl Use this command before ‘plot’ command
r=number of rows
c=number of columns
l=location of subplot on
figure window
Axis axis([ ]) To fix range of points on axis
Pause pause(n) To fix the time in seconds for drawing
n=number of seconds multiple graphs
Hold hold on Use plot command and then hold command
to plot multiple graphs on single axis
Line line(x , y) Use it after plot command to draw multiple
graphs on single axis.

2. 2-D Plot Functions:


Function name Description
( , ) 𝒔𝒆𝒎𝒊𝒍𝒐𝒈𝒙(𝒙,
𝒚) Plot with logarithmic scale x-axis and linear scale y-axis
( , ) 𝒔𝒆𝒎𝒊𝒍𝒐𝒈𝒚(𝒙,
𝒚) Plot with linear scale x-axis and logarithmic scale y-axis
( , ) 𝒍𝒐𝒈𝒍𝒐𝒈(𝒙, 𝒚) Plot with logarithmic scale x-axis and y-axis
( , )
𝒑𝒐𝒍𝒂𝒓(𝜽,𝒓) To draw a plot on polar axis coordinates
( , ) 𝒂𝒓𝒆𝒂(𝒙, 𝒚) Same as ‘plot’ command except area under curve is filled with color
𝒔𝒕𝒂𝒊𝒓𝒔(𝒙,𝒚,
′𝒔𝒕𝒚𝒍𝒆′) To give stair case plot
𝒄𝒐𝒏𝒕𝒐𝒖𝒓(𝒙,𝒚,
′𝒔𝒕𝒚𝒍𝒆′) To give contour of the given matrix

Style Options:
1. Color Style Options:

y = yellow m = magenta c = cyan


r = red g = green b = blue
w = white k = black
2. Marker Style Options:
. = point o = circle x = x-mark

+ = plus * = star s = square

d = diamond v = triangle (down) h = hexagram

^ = triangle (up) < = triangle (left)

>= triangle (right) p = pentagram

3. Line Style Options:


For Solid line= - For Dashed line= --
For Dotted line=. For Dashed dotted line= -.

ILLUSTRATIVE PROGRAMS:

Task#01:
Plot a curve for the equation
= 3+2 2−5, −10< <10.
Use labels, title and gtext command to write this equation on the curve plotted?

Program:
x=-10:1:10;
y=x.^3+2*x.^2-5;
plot (x,y)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('2D Graph');
gtext ('y=x^3+2*x^2-5');
grid on
OUTPUT:
Task#02:
Write a program to illustrate the use of area command with specified limits, for plot of function  
y=cos x for x=0 to π with step size of 0.02?
Program:
x=0:0.02:2*pi;
y=cos(x);
area (x,y)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing s single plot with filled area using Area Command'); gtext ('Filled Area');
OUTPUT:

Task#03:

Write a program to draw the curves for functions in a single figure window using single plot
command. Illustrate the use of different styles of curves which can be drawn using plot
command?
 y1=sin x
 y2=sin (x-0.35)
 y3=sin (x-0.55 )
 y4=sin (x-0.85) 

Program:
x=0:pi/10:2*pi;
y1=sin(x);
y2=sin(x-0.35);
y3=sin(x-0.55);
y4=sin(x-0.85);
plot (x,y1,'k-o' , x,y2,'g-o' , x,y3,'b-o' , x,y4,'m-o','linewidth',2)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing multiple plotsin a single figure window using plot command');
legend('y1=sin(x)','y2=sin(x-0.35)','y3=sin(x-0.55)','y4=sin(x-0.85)')
grid on;
axis tight

OUTPUT:

Task#04:
Write a program to draw the curves for function 
 y=200sin x *e-0.5x
 y=0.8sin 10x *e-0.5x
Illustrate how the “Legend” command is used to indicate the different styles used for the
different curves plotted on same graph?

Program:

x=0:0.01:100;
y1=200*exp(-0.5*x).*sin(x);
y2=0.8*exp(-0.5*x).*sin(10*x);

plot (x,y1,'g',x,y2,'c')
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing multiple plots using plot command');
legend ('y1=200*exp(-0.5*x).*sin(x)','y2=0.8*exp(-0.5*x).*sin(10*x)');

grid on
axis tight

OUTPUT:

Task#05:
Write a program to draw the curves for functions in a single figure window using using Hold and
Plot Command? 
 y1=sin x
 y2=sin (x-0.35)
 y3=sin (x-0.55 )
 y4=sin (x-0.85) 

Program:
x=0:pi/10:2*pi;
y1=sin(x);
plot (x,y1, 'b-.o','linewidth',2)
pause (2)

hold on

y2=sin(x-0.35);
plot (x,y2,'c-.o','linewidth',2)
pause (2)
y3=sin(x-0.55);
plot (x,y3,'r-.o','linewidt',2)
pause (2)

y4=sin(x-0.85);
plot (x,y4,'m-.o','linewidth',2)
pause (2)
hold off

xlabel ('X-Axis');
ylabel ('Y-Axis');
title('Graphing multiple curves using Hold Command');
grid on
axis tight

OUTPUT

Task#06:
Write a program to draw the curves for functions in a single figure window using Line
Command?
 y1=sin x
 y2=sin (x-0.35)
 y3=sin (x-0.55 )
 y4=sin x-0.85

Program:
x=0:pi/10:2*pi;
y1=sin(x);
y2=sin(x-0.35);
y3=sin(x-0.55);
y4=sin(x-0.85);
plot (x,y1, 'r-o','linewidth',2)
pause (2)
plot(x,y2, 'b-box','linewidth',2)
pause (2)

plot(x,y3, 'g-*','linewidth',2)
pause (2)

plot(x,y4, 'k-d','linewidth',2)
pause (2)

xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing multiple plots using Line Command');
legend
legend ('y1=sin(x)','y2=sin(x-0.35)','y3=sin(x-0.55'),'y4=sin(x-0.85)');
('y1=sin(x)','y2=sin(x-0.35)','y3=sin(x-0.55'),'y4=sin(x-0.85)');
grid on
axis tight

OUTPUT:

Task#07:
Divide the Figure window into four sub-windows and plot the following functions?
 Plot V versus I where V=4I and I=1,2,3,4 on the upper left sub-window.
 Plot y versus x where y=x2 and x=1,2,3,4 on the upper right sub-window.
 For t=0:2π in steps of t=60. Plot sin t versus t on the lower left window
 For t=0:30:2π. Plot cos t versus t on the lower right window.

Program:
I=1:1:4;
V=4*I;
subplot (2,2,1)
plot(I,V)
title('V Versus I');

x=1:1:4;
y=x.^2;
subplot (2,2,2)
plot(x,y)
title('y Versus x');

t=0:pi/60:2*pi;
Y=sin(t);
subplot (2,2,3)
plot(t,Y)
title('t Versus Sint');

t=0:pi/60:2*pi;
Y1=cos(t);
subplot (2,2,4)
plot(t,Y1)
title('t Versus Cost');

OUTPUT:

Task#08:
 Plot the following functions on the polar plot: 
f(θ) = sin 4θ   , -π2<θ<2, Where θ is in radians?
Program:
theta=-pi/2:pi/40:pi/2;
f=sin(4*theta);
polar (theta,f,'m-')
title ('Graphing using Polar Function')

OUTPUT:

Task#09:
a. Draw the stairs plot to show the function y=x2where -2≤x≤2
b. Draw the stairs plot for the following data:
X=[0 2 3 4 5 7]
Y=[5 -1 8 4 7 3]

Program:
X=-2:0.1:2;
Y=X.*X;
stairs(X,Y,'r','linewidth',2)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing stairs plot using stairs Command'); grid on
%%
X=[023457];
Y=[5 -1 8 4 7 3];
stairs(X,Y,'*-','linewidth',2)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing stairs plot using stairs Command');
grid on

OUTPUT:
Task#10:
Draw the stem plot for the following data:
X=[0 1 2 3 4 5 6]
Y=[3 -1 6 -4 5 2 3]

Program:
X=[0123456];
Y=[3 -1 6 -4 5 2 3];
Stem(X,Y,'k','linewidth',2.5)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing stairs plot using stairs Command'); grid on

OUTPUT:
Conclusion:

Following lab has taught us about another use of MATLAB that is graphs we have studied
different commands and algorithms that how should we apply them on MATLAB and for sure
we have practiced them Also the task that were assigned to us help us alot. Graphs has many
uses in real life such as Graphs model the connections in a network and are widely applicable to
a variety of physical, biological, and information systems. You can use graphs to model the
neurons in a brain, the flight patterns of an airline, and much more. The structure of a graph is
comprised of “nodes” and “edges”. Each node represents an entity, and each edge represents a
connection between two nodes.
Process Modelling & Simulation Wah Engineering College

LAB#6:
CONSTRUCTION OF 3-DIMENSIONAL GRAPHS IN MATLAB
The learning objectives are:
 To learn the basic features of plotting a 3D graph
 To draw multiple plots using ‘plot’, ‘hold’ and ‘line’ functions
 To learn about different style options to vary color, marker and line-style in 3D graphs.
Introduction:
MATLAB provides functions for visualizing 3-D scalar and the 3-D vector data. In MATLAB, one
can specify plot characteristics, such as viewing angle, perspective, lighting effect, light source,
location and transparency. 3-dimenstional plotting function includes surface, contour, mesh, image
plots simple and easily understandable. This makes graphics one of the most powerful features of
MATLAB.
MATLAB provides very good tools for 3-dimensional plots, 3-D volume visualization, functions,
tools for interactively creating plots and the ability to export results to many popular graphics
formats. It is possible to customized plots by adding multiple axes, changing line colors and markers,
adding annotation and legends.
List of 3D Graphic Commands:
Function Description
plot 3 ( x , y , z ) To plot a simple 3D plot.
[ X , Y ] =meshgrid (x , y) To give array for mesh grid
mesh( x , y , z) To plot wireframe mesh plot
surf ( x , y , z) To plot surface plot
meshc (x , y , z) To show shadow or circles beneath graph
meshz (x , y , z) To show curtains beneath graph
surfc( x , y , z) To plot shadow beneath surface
contour 3 ( x , y , z ) To give contour over the plane
waterfall ( x , y , z ) To show lines of 3D graph like waterfall
stem 3(x , y , z) To draw the discrete surface as stems
comet 3(x , y , z ) To see graph while drawing
ILLUSTRATIVE PROGRAMS:

Task#01:
Given is y=sin x∧z =x+5 , for 0< x <5000
Obtain a 3D plot.

Program:

27 | P a g e
Process Modelling & Simulation Wah Engineering College

x=0:0.02:5000;
y=sin(x);
z=x+5;
plot3(x,y,z)
xlabel ('X-Axis');
ylabel ('Y-Axis');
zlabel ('Z-Axis');
title ('Plot 3D Graph');
grid on;

OUTPUT:

Task#02:
Given is y=sin x∧z =x+5 , for 0< x <5000
Obtain a 3D plot using a Comet Command?

Program:

x=0:0.02:5000;
y=sin(x);
z=x+5;
comet3(x,y,z) %OR comet3(x,y,z) we see graph is drawn
xlabel ('X-Axis');
ylabel ('Y-Axis');
zlabel ('Z-Axis');
title ('Use of Comet Command');
grid on
axis tight

28 | P a g e
Process Modelling & Simulation Wah Engineering College

OUTPUT:

Task#03:
sin r
Create a surface plot of the function: z=
r
where r =√ x 2 + y 2 for−8< x <8∧−8< y < 8?

PROGRAM:
x=-8:0.5:8;
y=-8:0.5:8;
[X,Y]=meshgrid(x,y); % x and y changed into X,Y(now we use these X and Y)
r=sqrt(X.^2+Y.^2);
Z=sin(r)./r;
surf(X,Y,Z)
OUTPUT:

29 | P a g e
Process Modelling & Simulation Wah Engineering College

Task#04:
sin r
Create a mesh plot of the function: z=
r
where r =√ x + y for−8< x <8∧−8< y < 8?
2 2

PROGRAM:
x=-8:0.5:8;
y=-8:0.5:8;
[X,Y]=meshgrid(x,y); %x and y changed into X,Y(now we use these X and Y)
r=sqrt(X.^2+Y.^2);
Z=sin(r)./r;
mesh(X,Y,Z)

OUTPUT:

30 | P a g e
Process Modelling & Simulation Wah Engineering College

Task#05:
sin r
Plot the function using “meshc”, “meshz” and “waterfall” commands using the function z= where
r
r =√ x + y for−8< x <8∧−8< y < 8. Create subplots for each command.
2 2

PROGRAM:
x=-8:0.5:8;
y=-8:0.5:8;
[X,Y]=meshgrid(x,y);
r=sqrt(X.^2+Y.^2);
Z=sin(r)./r;

subplot (3,1,1);
meshc(X,Y,Z)
title ('meshc Graph');

subplot (3,1,2);
meshz(X,Y,Z)
title ('meshz Graph');
subplot (3,1,3);
waterfall(X,Y,Z)
title ('waterfall Graph');

OUTPUT:

31 | P a g e
Process Modelling & Simulation Wah Engineering College

Task#06:
Write a program to illustrate the use of stem3 function to plot the following function:
y=x cos x∧z=cosx e x/ 5+1 for 0 ≤ x ≤6 π

Program:
x=0:0.05:6*pi;
y=x.*cos(x);
z=exp(x/5).*cos(x)+1;
stem3(x,y,z)
xlabel ('X-Axis');
ylabel ('Y-Axis');
zlabel ('Z-Axis');
title ('Use of stem3 Command');
grid on
axis tight

OUTPUT:

32 | P a g e
Process Modelling & Simulation Wah Engineering College

CONCLUSION:
In this lab we have studied the basic features in detail by plotting 3-D graphs. we will summarize
the basic functions to create different types of plots. Here's how we use 3-D graphs, color,
markers and line styles.

33 | P a g e
Process Modelling & Simulation Wah Engineering College

LAB#10:
IMPLEMENTATION OF CODE OF NEWTON RAPHSON METHOD,
FIXED POINT METHOD AND SECANT METHOD FOR SOLUTION OF
TRANSCENDENTAL EQUATIONS

The learning objectives are:


 How does Open Methods work?
 Background of Open Methods.
 Algorithm.
 Convergence sheet.

1. NEWTON-RAPHSON METHOD:
ALGORITHM:
The steps of the Newton-Raphson method to find the root of an equation f ( x )=0 are
'
 Evaluate f ( x ) symbolically

x i , to estimate the new value of the root, x i+1 , as
Use an initial guess of the root,
f ( xi)
x i+1 = xi − '
f ( xi)

 Find the absolute relative approximate error a as


|∈ |
x i+1− x i
|∈a| = | |×10 0
x i+1
 Compare the absolute relative approximate error with the pre-specified relative error
∈ |∈ | ∈
tolerance, s . If a > s , then go to Step 2, else stop the algorithm. Also, check if
the number of iterations has exceeded the maximum number of iterations allowed. If
so, one needs to terminate the algorithm and notify the user.

MATLAB CODE:
TASK:

A mass balance for a pollutant in a well-mixed lake can be written as:

dc
v =w−Qc−kv √c
dt

Given the parameter values as follows:


6 3
v=1× 10 m
5 3
Q=1 ×10 m / year
34 | P a g e
Process Modelling & Simulation Wah Engineering College

6
w=1 ×10 gm/ year
0.5 0.5
k =0.25 m / g / year
The equation takes the form:

25 √ c+ 10 c−100=0

Solve for the steady-state concentration, find the root using Newton-Raphson method in
MATLAB.

PROGRAM:

f=@(x) 25*sqrt(x)+10*x-100 % Let steady-state concentration = x


Df=@(x) 12.5*x^(-1/2)+10;
f(0)
f(5)
f(10)
fplot(f,[0,10])
xlabel ('Steady-state concentration, c');
ylabel ('f(c)');
title ('NEWTON RAPHSON METHOD');
grid on
gtext('xr');

xa=10; % Initial Guess

fprintf ('i xa xr f(xr) RE\n');

for i=1:15

xr=xa - (f(xa)/Df(xa));
f_xr=25*sqrt(xr)+10*xr-100;
Df_xr=12.5*xr^(-1/2)+10;
RE=abs((xr-xa)/xr)*100;
xa=xr;
fprintf ('%6d %15.5f %15.5f %15.5f %18.5f \n' , i,xa,xr,f_xr,RE);

end %End of For-Loop Statement

fprintf('The root of given equation = %f \n' , xr);


OUTPUT:

35 | P a g e
Process Modelling & Simulation Wah Engineering College

f=

function_handle with value:

@(x)25*sqrt(x)+10*x-100

ans =

-100

ans =

5.9017

ans =

79.0569

i xa xr f(xr) RE
1 4.33399 4.33399 -4.61447 130.73415
2 4.62232 4.62232 -0.02787 6.23770
3 4.62408 4.62408 -0.00000 0.03812
4 4.62408 4.62408 0.00000 0.00000
5 4.62408 4.62408 0.00000 0.00000
6 4.62408 4.62408 0.00000 0.00000
7 4.62408 4.62408 0.00000 0.00000
8 4.62408 4.62408 0.00000 0.00000
9 4.62408 4.62408 0.00000 0.00000
10 4.62408 4.62408 0.00000 0.00000
11 4.62408 4.62408 0.00000 0.00000
12 4.62408 4.62408 0.00000 0.00000
13 4.62408 4.62408 0.00000 0.00000
14 4.62408 4.62408 0.00000 0.00000
15 4.62408 4.62408 0.00000 0.00000
The root of given equation = 4.624081
GRAPH:

36 | P a g e
Process Modelling & Simulation Wah Engineering College

SECANT METHOD:
ALGORITHM:
The Newton Raphson method of solving a non-linear equation of f (x)=0 is given by the
iterative formula:
f ’( x)=((f (xi) – f (xi−1))/( xi – xi−1)).

One of that’s method drawback is that we find derivative of that function, with availability of
symbolic manipulator like math, MAT-Lab and they are more convenient, laborious, intractable
if function derive as part of numerical scheme. In overcome that drawback th function derivative
is reduce to:
Put in above formula:
Xi +1=xi – ¿
The above eq. Is called the Secant Method, requires 2 initial guesses and no need to bracket the
root of the eq. It is an open method or may converge and faster than the Bi-Sectional Method but
slower than Newton Raphson Method.
The Newton-Raphson method of solving a nonlinear equation f (x )=0 is given by the iterative
formula

37 | P a g e
Process Modelling & Simulation Wah Engineering College

f (x i )
x i+1 = xi −
f ' ( xi)
One of the drawbacks of the Newton-Raphson method is that you have to evaluate the derivative
of the function. With availability of symbolic manipulators such as Maple, MathCAD,
MATHEMATICA and MATLAB, this process has become more convenient. However, it still
can be a laborious process, and even intractable if the function is derived as part of a numerical
scheme. To overcome these drawbacks, the derivative of the function, f (x ) is approximated as
' f ( x i )−f ( x i−1 )
f ( x i )=
x i −xi−1 (2)
Substituting Equation (2) in Equation (1) gives
f ( x i )( xi −x i−1 )
x i+1 =x i−
f (x i )−f ( x i−1 ) (3)
The above equation is called the secant method. This method now requires two initial guesses,
but unlike the bisection method, the two initial guesses do not need to bracket the root of the
equation. The secant method is an open method and may or may not converge. However, when
secant method converges, it will typically converge faster than the bisection method. However,
since the derivative is approximated as given by Equation (2), it typically converges slower than
the Newton-Raphson method

MATLAB CODE:
TASK

A mass balance for a pollutant in a well-mixed lake can be written as:

dc
v =w−Qc−kv √c
dt

Given the parameter values as follows:


6 3
v=1× 10 m
5 3
Q=1 ×10 m / year
6
w=1 ×10 gm/ year
0.5 0.5
k =0.25 m / g / year
The equation takes the form:

25 √ c+ 10 c−100=0

Solve for the steady-state concentration, find the root using Secant method in MATLAB.

38 | P a g e
Process Modelling & Simulation Wah Engineering College

PROGRAM:
f=@(x) 25*sqrt(x)+10*x-100 % Let steady-state concentration = x
f(0)
f(5)
f(10)
fplot(f,[0,10])
xlabel ('Steady-state concentration, c');
ylabel ('f(c)');
title ('Secant METHOD');
grid on
gtext('xr');

xa=0;
xb=10;
f_xa=@(x) 25*sqrt(xa)+10*xa-100;
f_xb=@(x) 25*sqrt(xb)+10*xb-100;

fprintf ('i xa xb xr f(xr) RE\n');

for i=1:20
xr=(xa*f(xb)-xb*f(xa))/(f(xb)-f(xa));
f_xr=25*sqrt(xr)+10*xr-100;
RE=abs((xr-xa)/xr)*100;

fprintf ('%6d %15.7f %15.7f %15.7f %15.7f %18.8f \n' , i,xa,xb,xr,f_xr,RE);


xa=xb;
f_xa=f_xb;

xb=xr;
f_xb=f_xr;

end
fprintf ('\n The root of given equation = %f \n' , xr);

OUTPUT:
f=

function_handle with value:

@(x)25*sqrt(x)+10*x-100

ans =

-100
39 | P a g e
Process Modelling & Simulation Wah Engineering College

ans =

5.9017

ans =

79.0569

i xa xb xr f(xr) RE
1 0.0000000 10.0000000 5.5848156 14.9286921 100.00000000
2 10.0000000 5.5848156 4.5569858 -1.0623985 119.44330174
3 5.5848156 4.5569858 4.6252716 0.0188273 20.74567944
4 4.5569858 4.6252716 4.6240825 0.0000253 1.45102891
5 4.6252716 4.6240825 4.6240809 -0.0000000 0.02574892
6 4.6240825 4.6240809 4.6240809 -0.0000000 0.00003454
7 4.6240809 4.6240809 4.6240809 0.0000000 0.00000000
8 4.6240809 4.6240809 4.6240809 0.0000000 0.00000000
9 4.6240809 4.6240809 NaN NaN NaN
10 4.6240809 NaN NaN NaN NaN
11 NaN NaN NaN NaN NaN
12 NaN NaN NaN NaN NaN
13 NaN NaN NaN NaN NaN
14 NaN NaN NaN NaN NaN
15 NaN NaN NaN NaN NaN
16 NaN NaN NaN NaN NaN
17 NaN NaN NaN NaN NaN
18 NaN NaN NaN NaN NaN
19 NaN NaN NaN NaN NaN
20 NaN NaN NaN NaN NaN

The root of given equation = NaN


GRAPH:

40 | P a g e
Process Modelling & Simulation Wah Engineering College

Conclusion:
Following lab was supported victimization MATLAB for numerical issues by applying totally
different codes and techniques so as to extract graphs of appropriate inputs and
extract varied iterations as needed. Additionally we are going to sure be applying
some additional tricks and codes so as to resolve these ways.

41 | P a g e
Process Modelling & Simulation Wah Engineering College

Lab # 6:
Detailed Distillation Column Design

Simulate the system shown in the diagram below.

1. Generate a temperature profile plot inside the column. Also, generate a plot showing the water
and methanol composition in the column
2. If the column trays have a Murphree efficiency of 65%, and the reboiler and condenser have
an efficiency of 90%, what will be the heat duty for the reboiler and condenser?
3. Experiment with the sizing form for the column and determine the tray diameters if a bubble-
cap trays are used. What is the required column diameter? What is the range for the tray
diameters?
4. If we have a 8’ diameter, bubble cap trays with 6” weir height and 3” cap diameter. Perform
tray rating and determine the flooding factor and the pressure drop per tray
Perform:

42 | P a g e
Process Modelling & Simulation Wah Engineering College

Define the different types of property methods that can be applied. From the navigation bars, select
techniques. Pengrob is a good starting point. The peng robinson equation of state is commonly used to
simulate high-pressure hydrocarbon-containing systems..

The feed stream must be taken into account. Double-click on the feed stream in the main flow sheet or go
to stream streer in the navigation pan. Assign the feed composition, flowrate, and other parameters the
values shown below.

To represent your process, create a flowchart. Click the simulation button in the lower left corner of the
screen to enter the simulation environment. Add a simple distillation block to the flowsheet and connect
the feed, Distiilate, and bottom ports to the materials streams. A SUFFICIENT distillation column that
can simulate multiphase conditions. Liquids that aren't quite right. Rate control mixing is known as
simple distillation in the model palette's column section. Rename the stream if required.

43 | P a g e
Process Modelling & Simulation Wah Engineering College

Set the column's operating requirements. Select a total for the condenser and a number between 1 and 5
for the number of phases. Before you can start the simulation, you must first set the operational criteria. I
know what our feed flowrate is, but I don't know what the distillate flowrate is supposed to be, thus I can't
specify the distillate to feed ratio. A reflux ration of 4 will be recorded as a first guess. Set this number as
the stage at which the feed stream will enter the column. The stage number in this case is 90. The graphic
below illustrates this.

44 | P a g e
Process Modelling & Simulation Wah Engineering College

It is necessary to consider the feed stream. Go to stream streer in the navigation pan or double-click on
the feed stream in the main flow sheet. Assign the values provided below to the feed composition,
flowrate, and other parameters.
The reboiler selects it first since it is hysys recommended kind.Set the stage 1 condenser pressure to
300psig on the pressure tab. The remaining pressures will very certainly be inevitable. The reboiler and
condenser temperatures are assumed in this computation. On a weighted basis, the reflux ratio is set at 4.
The final simulated flowsheet is presented below once the simulation is complete. And the final results
that comes are shown below in figures.

45 | P a g e
Process Modelling & Simulation Wah Engineering College

46 | P a g e
Process Modelling & Simulation Wah Engineering College

Conclusion:
This 125 stage colum was based on designing the distillation column for the feed stock os ethane and
ethylene. It can be concluded that the process is capable for completing its operation successfully but dew
to some mistakes simulation was not completed I’m sure that will clear this column and will redesign
This process although. ALHAMDULILLAH I’ve learned from it

47 | P a g e
Process Modelling & Simulation Wah Engineering College

Lab # 7:
Problem Statement and Aspen plus Solution Problem:

A stream containing 68.5wt% ethylene with a total flowrate of 7.3 million lb/day is fed into a distillation
column consisting of 125 stages. It is desired to produce a distillate product stream containing a minimum
of 99.96 wt% ethylene with a total flowrate of 5 million lb/day. It is also desired that the bottoms product
contains no more than 0.10wt% ethylene. Determine if this separation is feasible. Dist-001 Revised: Oct
10, 2012 2
Assumptions:
-100% tray efficiency
- Total condenser
- 300 psig column operating pressure
- A refrigerant utility stream capable of condensing the ethylene mixture (not included in model)
- Feed mixture is at 350 psig and is a vapor
- 125 stages
- Feed enters column at stage 90
- Peng-Robinson equation of stat
Perform:
Firstly, pick the component as a pure sample from the component list.

Outline the many types of property methods available. From the navigation bars, choose techniques.
Pengrob is a fine place to begin. Modeling high-pressure hydrocarbon-containing systems with the peng
robinson equation of state is common.

48 | P a g e
Process Modelling & Simulation Wah Engineering College

It is necessary to consider the feed stream. Go to stream section in the navigation pan or double-click on
the feed stream in the main flow sheet. Assign the values provided below to the feed composition,
flowrate, and other parameters.

Choose the distillation column from the model pallette on the menu's top right side.

49 | P a g e
Process Modelling & Simulation Wah Engineering College

Fill up the necessary condition for the operation to be operate in distillation column by double clicking on
the icon and then filling adding the parameters values as given in the problem and assuming steady state
conditions.

To represent your method, create a flowchart. Click the simulation button in the lower left corner of the
screen to enter the simulation environment. Connect the feed, Distiilate, and bottom ports to the materials
streams and add a simple distillation block to the flowsheet. 

50 | P a g e
Process Modelling & Simulation Wah Engineering College

Assume the Pressure in the Condenser and Reboiler and also the pressure drop

Assume the reflux ratio as 1.3 which is taken from the literature.

51 | P a g e
Process Modelling & Simulation Wah Engineering College

After Completion the final are represented in new box where all parameters and results can are shown.

Conclusion:
The 40-stage column exceeded the Norm of 99 wt% ethylene, with the bottoms containing less than 1 wt
% ethylene. This column might then be assumed to be capable of accomplishing the separation necessary.
It was never completed, however, because to a variety of problems. However, after reviewing this lab, I
believe that Aspen Hysys enables us to design new equipment that meets very specific requirements.

Lab # 8:
A mixture containing 50% acetone and 50% water has to be separated into two streams one enriched in
acetone and other in water. The separated process consists of extraction of acetone from the water into
methyl isobutyl ketone which dissolves acetone but is nearly immiscible with water. The overall goal of
this problem to separate the feed stream which have a high purity.
Perform:
Firstly, pick the component as a pure sample from the component list.

52 | P a g e
Process Modelling & Simulation Wah Engineering College

Outline the many types of property methods available. From the navigation bars, choose techniques.
NRTL is a fine place to begin. Modeling high-pressure hydrocarbon-containing systems with the NRTL
equation of state is common.

Fill up the necessary condition for the operation to be operate in distillation column by double clicking on
the icon and then filling adding the parameters values as given in the problem and assuming steady state
conditions. In material stream 1

53 | P a g e
Process Modelling & Simulation Wah Engineering College

Fill up the necessary condition for the operation to be operate in distillation column by double clicking on
the icon and then filling adding the parameters values as given in the problem and assuming steady state
conditions. In material stream 3

54 | P a g e
Process Modelling & Simulation Wah Engineering College

Choose the Mixer from the model pallette on the menu's top right side.

55 | P a g e
Process Modelling & Simulation Wah Engineering College

Choose the Separator from the model pallette on the menu's top right side

56 | P a g e
Process Modelling & Simulation Wah Engineering College

Fill up the necessary condition for the operation to be operate in distillation column by double clicking on
the icon and then filling adding the parameters values as given in the problem and assuming steady state
conditions. In material stream 4

57 | P a g e
Process Modelling & Simulation Wah Engineering College

Fill up the necessary condition for the operation to be operate in distillation column by double clicking on
the icon and then filling adding the parameters values as given in the problem and assuming steady state
conditions. In material stream 5

58 | P a g e
Process Modelling & Simulation Wah Engineering College

After Completion the results represented in new box where all parameters and results can are shown

59 | P a g e
Process Modelling & Simulation Wah Engineering College

This is the final simulated process flow diagram of our process generated in aspen

60 | P a g e
Process Modelling & Simulation Wah Engineering College

Conclusion:
The Process is complete after filling the required information of mixers separator input and output steams
and also selecting the components and equation of models. This column might then be assumed to be
capable of accomplishing the separation necessary. It was never completed, however, because to a variety
of problems. However, after reviewing this lab, I believe that Aspen Hysys enables us to design new
equipment that meets very specific requirements.

61 | P a g e

You might also like