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

UNITED INTERNATIONAL UNIVERSITY (UIU)

Dept. of Electrical & Electronic Engineering (EEE)


Course: EEE 2000 / EEE 110
Course Title: Simulation Laboratory

Lab Sheet 1
Introduction to MATLAB Environment, Syntax,
Operators, Data Types, and Simple Mathematical
Operations
Prerequisite
Before starting this lab, students should know:
1. a fundamental knowledge on Matrix Algebra.
2. basic typing skills.
Outcome
After finishing this lab, students should be able to:
1. get familiarized about the MATLAB environment.
2. examine various MATLAB desktop and editing features.
3. use some simple MATLAB commands from the Command Window.
Outline of this lab
1. Lab Session 1.0: Introduction
2. Lab Session 1.1: Familiarization of the MATLAB Environment
3. Lab Session 1.2: Working on the Command Window
4. Lab Session 1.3: Real Life Problems
5. Lab Session 1.4: In Lab Evaluation
6. Home Work

Lab Session 1.0: Introduction


What is MATLAB: MATLAB stands for MATrix LABoratory. MATLAB is a software package for
computation in engineering, science, and applied mathematics. It offers a powerful programming
language, excellent graphics, and a wide range of expert knowledge. MATLAB is published by and a
trademark of the MathWorks, Inc.

Lab Session 1.1: Familiarization of the MATLAB


Environment
First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
1|Page
1.1.1 Starting MATLAB
When the MATLAB program starts, the following window opens which contains four smaller
windows. These windows are default and can be switched on or off if necessary, as shown in Figure
1.1. The window in the desktop that concerns us for now is the Command Window, where the special
>> prompt appears. This prompt means that MATLAB is waiting for a command.

1.1.2 Closing MATLAB


You can quit at any time with one of the following ways:
(a) Click the X (close box) in the upper right-hand corner of the MATLAB desktop.
(b) Type quit or exit at the Command Window prompt followed by pressing the Enter key.

Workspace
Current View
Directory Command window
program
View like a calculator
variables
and many more
folders
and m
files

Figure 1.1: MATLAB desktop

1.1.3 Four Most Used MATLAB Windows


Command Window This is where you type and execute commands.
This shows current variables and allows to edit variables by opening array
Workspace Window
editor (double click), to load variables from files and to clear variables.
Current Directory This shows current directory and MATLAB files in current folder, provides
Window with a handy way to change folders and to load files.

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
2|Page
This shows previously executed commands. Commands can be re-executed
History Window
by double-clicking.

Lab Session 1.2: Working in the Command Window


Guidelien of using Command Window:

Name Working description


command line The line with the >> prompt is called the command line.
To recall previous lines in the Command Window, press the up- and down-
command-line arrow keys (↑ and ↓ respectively). Press the arrow keys either at an empty
editing 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.
MATLAB has a useful editing feature called smart recall. Just type the first
few characters of the command you want to recall. For example, type the
smart recall
characters 2* and press the up-arrow key: this recalls the most recent
command starting with 2*.
clear a command
from the To clear a command from the Command Window without executing it, press
Command the Escape (Esc) key.
Window
execute only a In the Command Window, you also can execute only a portion of the code
portion of the currently at the command prompt. To evaluate a portion of the entered code,
code select the code, and then press Enter.
You can evaluate any statement already in the Command Window. Select the
statement, right-click, and then select Evaluate Selection.
evaluate any For example, select a portion of the following code:
statement >> disp('EEE'); disp('UIU')
The output is:
EEE

1.2.1 Using MATLAB as a Calculator


You can use command window for various calculations as if you would use a calculator: Type
expressions containing numbers, parenthesis and mathematical operations and press Enter to get the
result.
A. Entering Single Statements in Command Window
As you work in MATLAB, you can enter individual statements in the Command Window. For
example, create a variable named a by typing this statement at the command line:
a=1

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
3|Page
MATLAB immediately adds variable a to the workspace and displays the result in the
Command Window.
a=
1
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
The value of ans changes with every command that returns an output value that is not assigned
to a variable.
If you end a statement with a semicolon, MATLAB performs the computation, but suppresses
the display of output in the Command Window.
b = 2;
B. Entering Multiple Statements in Command Window
To enter multiple statements on multiple lines before running any of the statements, use Shift+Enter
between statements. This action is unnecessary when you enter a paired keyword statement on
multiple lines, such as for and end.
You also can enter more than one statement on the same line by separating statements. To
distinguish between commands, end each one with a comma or semicolon. Commands that end with
a comma display their results, while commands that end with a semicolon do not. For example, enter
the following three statements at the command line:
A = magic(5), B = ones(5) * 4.7; C = A./B
A=
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
C=
3.6170 5.1064 0.2128 1.7021 3.1915
4.8936 1.0638 1.4894 2.9787 3.4043
0.8511 1.2766 2.7660 4.2553 4.6809
2.1277 2.5532 4.0426 4.4681 0.6383
2.3404 3.8298 5.3191 0.4255 1.9149
MATLAB displays only the values of A and C in the Command Window.
Why is B not displayed?
C. Variable Naming Rules

Sl. Rules Examples Comment

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
4|Page
Must begin with letter of the alphabet. >> myvar = 4 Correct.
1. After the first character, it can contain >> 2num = 6 Incorrect.
special characters or numbers. >> rad23 = 2.3e3 Correct.
There is a limit to the length of a
variable name. Typically, ≤ 64 >> namelengthmax
Maximum length of a
2. characters. ans =
variable name is 63.
(Variable name should be as minimum 63
as possible but it should be meaningful)
>> mynum = 4
MATLAB is case-sensitive, so All are correct but have
3. >> MYNUM = 6
capitalization matters different meanings.
>> myNum = 8
Works, but should be
>> my_num = 5
avoided.
4. Avoid underscores. Use mixed case.
Much safer, still easy to
>> myNum = 5
read.

Certain words are reserved and cannot >> for = 4 This is not allowed, for is
5.
be used as variable names. a keyword.
Note:
Write
>> iskeyword
in command prompt. It will give the following output, means that the following are key word
and cannot be used as variable names.
Ans =
‘break’
‘case’
‘catch’
‘classdef’
‘continue’
‘else’
‘elseif’
‘end’
‘for’
‘function’
‘global’
‘if’
‘otherwise’
‘parfor’
‘persistent’
‘return’
‘spmd’

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
5|Page
‘switch’
‘try’
‘while’
Technically allowed but is
Names of built-in functions should not
6. >> sin = 2 bad programming style &
be used as variable names.
may cause problems.

>> aabcaded = 2 What is aabcaded?

temperatureInTopek
Variable names should be mnemonic & aKansasAug19Recor
7. Too long!
short. dedByChrisSmithTan
nerTheSecond = 2

>> tempKS = 2 Much better

D. Variable Assigning Rules


Values can be stored in variables using MATLAB. Variable goes on left and what you want to put
goes on right.
>> variablename = expression
>> a = 6
>> 6 = a %This gives an error!
>> mass = 2.5e9
E. List of Useful Commands for Managing Variables
Command Outcome
clear Removes all variables from memory.
clear x y z Removes only variables x,y,z from the memory .
who Displays a list the variables currently in the memory.
Displays a list the variables currently in the memory and their size together with
whos
information about their bytes and class.

F. Two Important Commands to Ensure Fairness and Readability


Command Outcome
clc Clears contents on the command window ensuring blank working environment.
If used before any line or statement, program ignores the line or statement.
%
Therefore, it is used for inserting any comment in the program.

G. Predefined Variables

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
6|Page
Several frequently used variables are already defined when MATLAB is started. Some of the
predefined variables are:
Predefined
Meaning
Variables
A variable that has the value of the last expression that has not been assigned to a
ans specific variable. If the user does not assign the value of an expression to a variable,
MATLAB automatically stores the result in ans.
Pi Value of the number 𝜋.
eps The smallest difference between two numbers. Its value is 2.2204e-016.
Inf Used for infinity.
i or j Defined as √−1
Stands for Not-a-Number. It is used when MATLAB cannot determine a valid
NaN
numeric value. As an example, 0/0.

H. Complex Numbers
MATLAB also supports complex numbers. The imaginary number is denoted with the symbol i or j,
assuming that you did not use these symbols anywhere in your program (that is very important!). Try
the following:
Expression Meaning
>> z =3 + 4i Assigns a complex number to variable z. Note that you do not need the ‘*’ after 4.
>> conj(z) Computes the conjugate of z.
>> angle(z) Computes the phase of z.
>> real(z) Computes the real part of z.
>> imag(z) Computes the imaginary part of z.
>> abs(z) Computes the magnitude of z.

I. Random Numbers
MATLAB can generate pseudo-random numbers which are useful for creating synthetic data or adding
noise.
Command Meaning
>> rand Gives a random floating point number between 0-1.
>> round(rand*10) To get random integers use “round”, rand integers from 0-10.
WARNING: rand will always give the exact same random number when
>> rng(‘shuffle’)
you first start. Use rng first to prevent this.

J. Elementary Math Functions used in MATLAB

Function Description Example


sqrt(x) Square root >> sqrt(16)

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
7|Page
ans =
4
>> exp(3)
exp(x) Exponential (𝒆𝒙 ) ans =
20.0855
>> abs(-4)
ans =
4
abs(x) Absolute value
>> abs(3+4j)
ans =
5
>> log(1000)
log(x) Natural logarithm (Base e) ans =
6.9078
>> log10(1000)
log10(x) Base 10 logarithm ans =
3
>> factorial(5)
The factorial function x!
factorial(x) ans =
(x must be a positive integer)
120
>> sin(pi/6)
sin(x) Sine of angle x (x in radians) ans =
0.5000
>> cos(pi/4)
cos(x) cosine of angle x (x in radians) ans =
0.7071
>> tan(pi/3)
tan(x) Tangent of angle x (x in radians) ans =
1.7321
>> tand(60)
tand(x) Tangent of angle x (x in degree) ans =
1.7321
>> asin(sqrt(3)/2)
ans =
asin(x) Inverse sine of x
1.0472
(Note that result is in radians)
>> round(17/5)
round(x) Round to the nearest integer ans =
3
>> ceil(11/5)
ceil(x) Round towards infinity
ans =

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
8|Page
3
>> floor(9/4)
floor(x) Round towards minus infinity ans =
2
>> rem(13,5)
Returns the remainder after x is
rem(x,y) ans =
divided by y
3
Signum function >> sign(-5)
sign(x) Returns 1 if x > 0 ans =
Returns -1 if x < 0 -1

K. Some Useful Commands while Using Command Window

diary Save Command Window text to file


home Send cursor home

L. Data Types in MATLAB


Every variable has a type associated with it. MATLAB supports many types, which are called classes.
(Essentially, a class is a combination of a type and the operations that can be performed on values of
that type, but, for simplicity, we will use these terms interchangeably for now.) For example, there are
types to store different kinds of numbers. For float or real numbers, or, in other words, numbers with
a decimal place (e.g., 5.3), there are two basic types: single and double. The name double is a short
form of double precision; it stores larger numbers than the single type.
MATLAB uses a floating point representation for these numbers. There are many integer
types, such as int8, int16, int32, and int64. The numbers in the names represent the number of bits
used to store values of that type. For example, the type int8 uses eight bits altogether to store the
integer and its sign. As one bit is used for the sign, this means that seven bits are used to store actual
numbers (0s or 1s). There are also unsigned integer types uint8, uint16, uint32, and uint64. For these
types, the sign is not stored, meaning that the integer can only be positive (or 0).
The range of a type, which indicates the smallest and largest numbers that can be stored in the
type, can be calculated. For example, the type uint8 stores 28 or 256 integers, ranging from 0 to 255.
The range of values that can be stored in int8, however, is from -128 to +127. The range can be found
for any type by passing the name of the type as a string (which means in single quotes) to the functions
intmin and intmax. For example,
>> intmin('int8')
ans =
-128
>> intmax('int8')
ans =
127

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
9|Page
The larger the number in the type name, the larger the number that can be stored in it. We will,
for the most part, use the type int32 when an integer type is required.
The type char is used to store either single characters (e.g., ‘x’) or strings, which are sequences
of characters (e.g., ‘cat’). Both characters and strings are enclosed in single quotes. The type logical
is used to store true/false values. Variables that have been created in the Command Window can be
seen in the Workspace Window. In that window, for every variable, the variable name, value, and
class (which is, essentially, its type) can be seen. Other attributes of variables can also be seen in the
Workspace Window. Which attributes are visible by default depends on the version of MATLAB.
However, when the Workspace Window is chosen, clicking on the down arrow allows the user
to choose which attributes will be displayed by modifying Choose Columns. By default, numbers are
stored as the type double in MATLAB. There are, however, many functions that convert values from
one type to another. The names of these functions are the same as the names of the types shown in this
section. These names can be used as functions to convert a value to that type. This is called casting
the value to a different type, or type casting. For example, to convert a value from the type double,
which is the default, to the type int32, the function int32 would be used. Entering the assignment
statement
>> val = 6 +3;
would result in the number 9 being stored in the variable val, with the default type of double, which
can be seen in the Workspace Window. Subsequently, the assignment statement
>> val = int32(val);
would change the type of the variable to int32, but would not change its value.
Here is another example using two different variables.
>> num=6+3
num =
9
>> whos
Name Size Bytes Class Attributes

num 1x1 8 double


numi 1x1 4 int32

Note that whos shows the type (class) of the variables, as well as the number of bytes used to
store the value of a variable. One byte is equivalent to eight bits, so the type int32 uses four bytes. The
function class can also be used to see the type of a variable.
One reason for using an integer type for a variable is to save space in memory.
M. Numerical Expressions
Expressions can be created using values, variables that have already been created, operators, built-in
functions, and parentheses. For numbers, these can include operators, such as multiplication, and
functions, such as trigonometric functions.
Sample Example-1
>> a=1;

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
10 | P a g e
>> b=2;
>> c=4;
>> d=5;
>> x= a^3+sqrt(b*d)-4*c
x=
-11.8377
Sample Example-2
>> a=2;
>> b=-3;
>> c=4;
>> x=5;
>> y=a*x^2+b*x+c
y=
39
Note the semicolon after each variable assignment. If you omit the semicolon, then MATLAB
echoes back on the screen the variable value.

N. The Format Function and Ellipsis


The default in MATLAB is to display numbers that have decimal points with four decimal places, as
shown in the previous examples. (The default means if you do not specify otherwise, this is what you
get.) The format command can be used to specify the output format of expressions. There are many
options, including making the format short (the default) or long. This will remain in effect until the
format is changed back to short, as demonstrated in the following:
Format / Ellipsis Example Comment
>> format long
>> format long >> 2 * sin(1.4) Changing the format to long will result
ans = in 15 decimal places.
1.970899459976920
>> format short
>> 2 * sin(1.4) Changing the format to short will result
>> format short
ans = in 4 decimal places.
1.9709
>> format bank
>> 22/7 Changing the format to bank will result
>> format bank
ans = in 2 decimal places.
3.14
> format loose
>> a=3
There are blank lines between command
>> format loose
and output.
a=

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
11 | P a g e
3.00
>> format compact
>> b=7 There is no spacing between command
>> format compact
b= and output.
7.00
Long expressions can be continued on
the next line by typing three (or more)
>> 3 +55 - 62 + 4 - 5…
periods, which is the continuation
+22-1
operator, or the ellipsis. To do this, type
Ellipsis ans =
part of the expression followed by an
16
ellipsis, then hit the Enter key and
continue typing the expression on the
next line.

O. Save or Load Workspace Variables to or from a File

Syntax Description Example


filename = 'test.mat';
save(filename) saves all variables from the current
save(filename)
workspace in a MATLAB formatted binary file (MAT-
save(filename) Otherwise, you also can
file) called filename. If filename already exists, save
use command syntax.
overwrites the file.
save test.mat
load(filename) You can retrieve the data with the load function load('test.mat')
p = rand(1,10);
q = ones(10);
Create and save two variables, p and q, to a file called save('pqfile.mat','p','q')
save(filename,
pqfile.mat. MATLAB saves the variables to the file, You also can use
variables)
pqfile.mat, in the current folder. command syntax to save
the variables, p and q.
save pqfile.mat p q
load(filename) You can retrieve the data with the load function. load(‘pqfile.mat’)

Lab Session 1.3: Real Life Problems


Example 1.1:
The circumference of an ellipse can be approximately as,
𝐶 = 𝜋[3(𝑎 + 𝑏) − √(3𝑎 + 𝑏)(𝑎 + 3𝑏)
Calculate the circumference of an ellipse with, a = 16, b = 11.

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
12 | P a g e
Solution:
Code:
a=16; b=11;
C=pi*(3*(a+b)-sqrt((3*a+b)*(a+3*b)))
Command Window:
C=
85.5518

Example 1.2:
The resonant frequency 𝑓(in Hz) for the circuit shown is given by,

1 1 𝑅 2
𝑓= √ −( )
2𝜋 𝐿𝐶 𝐿
Calculate the resonant frequency when, L = 0.15 H, R = 14 Ω and C = 2.6×10-6 F.

Solution:
Code:
L=0.15; R=14; C=2.6e-6;
f=1/(2*pi)*sqrt(1/(L*C)-(R/L)^2)
Command Window:
f=
254.4186

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
13 | P a g e
Lab Session 1.4: In Lab Evaluation
In this section, students will solve the following problem(s) during lab hour
by themselves.
ILE 01: After t seconds of switching, the voltage Vc is given by:
𝑉𝑐 = 𝑉0 (1 − 𝑒 −𝑡/𝑅𝐶 )
Given that Vo = 36 V, R = 2500 Ω and C=1000µF. Calculate the current in the circuit 8 sec after the
switch is closed.

Home Work:
HW 01 An object with an initial temperature of T0 that is placed at time t = 0 inside a chamber
that has a constant temperature of T3 will experience a temperature change according to
the equation:
𝑇 = 𝑇3 + (𝑇0 − 𝑇3 )𝑒 −𝑘𝑡
where T is the temperature of the object at time t, and k is a constant. A soda can at a
temperature of 120 °F (after being left in the car) is placed inside a refrigerator where the
temperature is 38 °F. Determine, to the nearest degree, the temperature of the can after
three hours. Assume k = 0.45 hr-1. First define all the variables and then calculate the
temperature using one MATLAB command.

HW 02 The arc length of a segment of a parabola ABC of an ellipse with semi-minor axes a and
b is given approximately as,
1 𝑏2 4𝑎 + √𝑏 2 + 16𝑎2
𝐿𝐴𝐵𝐶 = √𝑏 2 + 16𝑎2 + ln ( )
2 8𝑎 𝑏
Determine LABC if a = 11 cm and b = 9 cm.

First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
14 | P a g e
First OBE version, prepared by: B.K.M Mizanur Rahman, Assistant Professor, Department of EEE, UIU
Updated on Summer 2021, by Dr. Sadid Muneer, Assistant Professor, Department of EEE, UIU
15 | P a g e

You might also like