Course Name Simulation and Computational Laboratory: by Belaynesh Belachew (Lec.)
Course Name Simulation and Computational Laboratory: by Belaynesh Belachew (Lec.)
By
Belaynesh Belachew (Lec.)
Lab Instructions
When you attend to this lab you must follow the following
instructions:
1. Attend on your time, not before not after;
2. Try to use the same computer every time ;
3. Make a folder with your name and save the programs you
perform at this folder, (this important for your evaluation).
• Introduction
• Matlab fundamentals
• Logical Vectors
• Matrices
• Introduction to graphics
• Loops
• Simulink
• Application of Matlab in the field of electrical
• Simple calculations
• Window Purpose
window
Workspace window provides information about the variables
that are used
Current Folder shows the files in the current directory
09/13/2021 Defence univerisity,Collage of Engineering 9
09/13/2021 Defence univerisity,Collage of Engineering 10
MATLAB Basics
• In MATLAB, every expression, or variable, has a type associated with it.By
default, numbers are stored as the type double(short for double-precision).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.
• MATLAB uses double-precision floating point arithmetic accurate to
approximately 15 digits, however,only 5 digits are displayed, by default. To
display more digits, type format long. Then all subsequent numerical output will
have 15 digits displayed. Type format short to return to 5-digit display.
• who: who will give more details which include size, space allocation, and class
of the variables.
• clc: To clear the Command Window
• ctrl-c: To abort a MATLAB computation
• . . . : To continue a line
The find function determines the index of array elements that meet a given logical condition. The
function is useful for creating masks and index matrices. In its most general form, find returns a
single vector of indices. This vector can be used to index into arrays of any size or shape.
For example,
A = magic(4)
A=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
A=
100 2 3 100
5 100 100 8
100 7 6 100
09/13/2021 Defence univerisity,Collage of Engineering 20
4 100 100 1
You can also use
Example
Find to obtain both the row and column indices of a rectangular matrix for the array values that meet the
logical condition:
A = magic(4)
A=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
[row, col] = find(A > 12)
Ans
row =
1
4
4
1
col =
1
2
3
4
09/13/2021 Defence univerisity,Collage of Engineering 21
MATRICES
• MATLAB supports two types of operations, known as matrix operations and array
operations. Matrix operations will be discussed first.
Example
v = [1 4 7 10 13]
>> A(2,1)
A(2,1) is an element located in the second row and first column. Its value is 4
>> A(3,3) = 0
Often we must deal with matrices or vectors that are too large to enter one element
at a time. For example, suppose we want to enter a vector x consisting of points
(0, 0.1, 0.2, 0:3,...,5). We can use the command.
>> x = 0:0.1:5;
The row vector has 51 elements.
It is similar to the colon operator (:), but gives direct control over the number
of points. For example,
>> y = linspace(a,b,n)
generates a row vector y of n points linearly spaced between and including a
and b
The colon operator can also be used to pick out a certain row or column. For
example, the statement A(m:n,k:l) specifies rows m to n and column k to
l. Subscript expressions refer to portions of a matrix. For example,
>> A(2,:); is the second row elements of A.
>> B = A([2 3],[1 2]); extract a submatrix B consisting of rows 2 and 3 and columns 1
It is important to note that the colon operator (:) stands for all columns or all rows.
As a special case, a colon (:) as the row or column speci¯er covers all entries in that
• Multiplication
• Inverse
b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
• A=matrix of coefficients,
• x = vector of variables,
• b = vector of values.
• In matrix form the above system and its solution can be written as
• The rot90 function rotates the matrix counterclockwise 90 degrees, so, for example, the
value in the top right corner becomes instead the top left corner and the last column
becomes the first row.
mat
>> rot90(mat)
ans =
94 47 42
2 75 45
61 28 20
14 21 20
09/13/2021 Defence univerisity,Collage of Engineering 39
Differentiation:
The MATLAB symbolic toolbox is very useful for checking calculus problems.
For example, to find diff_f = where f = e-axx3bsin(cx) and a, b and c are
unspecified constants, we do the following
syms x
f=exp(-a*x)*a^(3*x)*sin(c*x);
diff_f = diff(f,x)
2
complex. To ask MATLAB to try to
dx
simplify it, type:
>> diff_f_simp = simple(diff_f)
• The first step is to tell MATLAB that the variables to be used are symbolic.
This is most easily done using the “syms” command. For example, in the
following we will use x, y, a, b and c as symbolic quantities. So enter:
>> syms x y a b c f g
In the Workspace window (or use >> whos) note that these variables are
symbolic, rather than the usual double precision numeric variables.
• Evaluate
Matlab program
• Create a vector to represent the polynomial
p = [3 0 -4 10 -25];
q = polyint(p)
p = [3 0 -4 10 -25]; a = -1;
Use polyint to integrate the polynomial using b = 3;
a constant of integration equal to 0.
I = diff(polyval(q,[a b]))
q = polyint(p)
q = 0.6000 0 -1.3333 5.0000
-25.0000 0
Find the value of the integral, I, by evaluating
q at the limits of integration.
a = -1;
b = 3;
I = diff(polyval(q,[a b]))
Answer I = 49.0667
09/13/2021 Defence univerisity,Collage of Engineering 44
Integrate Product of Two Polynomials
Evaluate
p = [1 0 -1 0 0 1];
v = [1 0 1];
k = 3;
q = polyint(conv(p,v),k)
a = 0;
b = 2;
I = diff(polyval(q,[a b]))
negligible
09/13/2021
column elements. Defence univerisity,Collage of Engineering 51
Cont…
The "hold on" command tells MATLAB to write the following plots on top of the first
one, rather than replacing it. Approximate values of the solutions (intersections) can
be obtained in the Figure window by clicking on Tools / Zoom In, clicking on a
desired intersection to enlarge that area of the graph, clicking on Tools / Data Cursor,
and then clicking on that intersection again to give the approximate values of x and y
there. Compare these results with those found above using the solve command.
There are cases where the limit depends on the direction from which it is approached.
Consider the plot of tan(x) versus x generated by:
Suppose we want the value of tan(x) at x = /2. We could use MATLAB's numeric engine as follows:
>> tan(pi/2)
Does this give a correct result? Recall that tan(/2) can be either + or -, depending on whether we
approach from the left or the right.
We can use the symbolic engine to find the two correct solutions, as follows:
>> clear, syms x, tanhalfpiright = limit(tan(x),x,pi/2,'right')
>> 09/13/2021 Defence univerisity,Collage of Engineering
tanhalfpileft = limit(tan(x),x,pi/2,'left') 54
MATLAB M-Files
After creating and saving the file, you can run it in two ways −
Clicking the Run button on the editor window or Just typing the filename (without
extension) in the command prompt :
The command window prompt displays the result −
6170
a = 5;
b = 7;
c=a+b
d = c + sin(b)
e=5*d
f = exp(-d)
When the above code is compiled and executed, it produces the following result −
• c = 12 d = 12.657 e = 63.285 f = 3.1852e-06
• Function M-files
• Function M-files accept input arguments and produce output. Note that it is
appropriate to use inline functions for defining simple functions that can be
expressed in one line. Function M-files are useful for defining functions
that require several commands to compute the output.
function [output_parameters] = function_name (input_parameter)
>>x=linspace(0,4*pi,100);
• Calculate sin(.) of the x-array
1
0.8
0.6
>>y=sin(x);
0.4
-0.2
-0.4
-0.6
>>plot(y) -0.8
-1
0 10 20 30 40 50 60 70 80 90 100
>>plot(y2) 0.6
0.5
0.4
0.3
0.2
0.1
-0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
0.6
0.5
• plot(.) 0.4
0.3
Example:
0.2
0.1
>>x=linspace(0,4*pi,100); 0
>>y=sin(x); -0.1
>>plot(y) -0.2
>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100
0.7
• stem(.) 0.6
0.5
0.4
0.3
Example:
0.2
0.1
>>stem(y) 0
>>stem(x,y) -0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
0.8
• xlabel(.) 0.6
0.4
sin(x)
0
• ylabel(.)
-0.2
-0.4
-0.6
-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
ans
% Plot a sine curve:
x = -pi:.1:pi;
y = sin(x);
plot(x,y)
2. Create line plot using specific line width, marker color, and marker size:
09/13/2021 Defence univerisity,Collage of Engineering 66
Ans
Create line plot using specific line width, marker color, and marker size:
x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));
plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
You can display multiple plots in the same Figure window and print them on
the same piece of paper with the Subplot function.
subplot(m,n,i) breaks the Figure window into an m-by-n matrix of small sub-
plots and selects the ith subplot for the current plot. The plots are numbered
along the top row of the Figure window, then the second row, and so forth.
For example, the following statements plot data in four different subregions of
the Figure window.
1.For a matrix, the bar and barh functions will group together the values in each
row are 1st and 2nd groups are 8 19 43 25; 35 44 30 45 respectively.
For example:
%groupages = [8 19 43 25; 35 44 30 45]
groupages =
8 19 43 25
35 44 30 45
>> bar(groupages)
>> xlabel('Group')
>> ylabel('Ages')
When using Word, to get straight quotation marks click on the File tab, then
Options/Proofing/Auto Format and click off "Straight quotes" with “smart quotes”. Do
the same with Auto Correct Options/ Auto Format As You Type.
Three-dimensional plots can be created using the ezmesh and ezsurf commands. For these commands an explicit form must be
used, i.e. z = f(x,y). It is the f(x,y) that is entered into the command. The code below illustrates some possibilities. The lines
with % are comments and are not executed by MATLAB. Open the excellent MATLAB editor by >> edit, cut and paste the code
below into your editor, save it on your Current Directory as symplot3D.m, make certain the Current Directory is in MATLAB’s
path (File/Set Path).
% symplot3D.m
% Some 3d plots, where z = the expressions shown
% In the figure window, click on Tools, Rotate 3D.
% Then put cursor on figure, hold down left mouse,
% move cursor to rotate figure. Notice that this
% gives you a better feeling for its 3D shape.
% Have some fun and create your own shapes.
clear, clc
syms x y
ex1='sqrt(4-x^2-y^2)';
figure(1); ezsurf(ex1,[-2,2,-2,2]);
ex2='x^2-y^2';
figure(2); ezsurf(ex2);
ex3='x^2+2';
figure(3); ezmesh(ex3);
ex4='x + y';
figure(4); ezmesh(ex4);
Select each figure in turn, and in the Figure window Tools / Rotate 3D. Put the cursor anywhere on the figure, hold down the left
mouse09/13/2021
button, and move the mouse to rotate Defence univerisity,Collage of Engineering
the figure. 73
Three-dimensional plots
Three-dimensional plots can be created using the ezmesh and ezsurf commands. For these commands an explicit form must be
used, i.e. z = f(x,y). It is the f(x,y) that is entered into the command. The code below illustrates some possibilities. The lines
with % are comments and are not executed by MATLAB. Open the excellent MATLAB editor by >> edit, cut and paste the code
below into your editor, save it on your Current Directory as symplot3D.m, make certain the Current Directory is in MATLAB’s
path (File/Set Path).
% symplot3D.m
% Some 3d plots, where z = the expressions shown
% In the figure window, click on Tools, Rotate 3D.
% Then put cursor on figure, hold down left mouse,
% move cursor to rotate figure. Notice that this
% gives you a better feeling for its 3D shape.
% Have some fun and create your own shapes.
clear, clc
syms x y
ex1='sqrt(4-x^2-y^2)';
figure(1); ezsurf(ex1,[-2,2,-2,2]);
ex2='x^2-y^2';
figure(2); ezsurf(ex2);
ex3='x^2+2';
figure(3); ezmesh(ex3);
ex4='x + y';
figure(4); ezmesh(ex4);
Select each figure in turn, and in the Figure window Tools / Rotate 3D. Put the cursor anywhere on the figure, hold down the left
mouse09/13/2021
button, and move the mouse to rotate Defence univerisity,Collage of Engineering
the figure. 74
Loops
The for statement, or the for loop, is used when it is necessary to repeat
statement(s) in a script or function, and when it is known ahead of
time how many times the statements will be repeated. The statements
that are repeated are called the action of the loop. For example, it may
be known that the action of the loop will be repeated five times. The
terminology used is that we iterate through the action of the loop five
times.
For example , the variable might iterate through the integers 1 through 5
(e.g., 1, 2, 3, 4, and then 5). Although, in general, variable names
should be mnemonic, it is common in many languages for an iterator
variable to be given the name i (and if more than one iterator variable
is needed, i, j, k, l, etc.).
Answer
In a loop, you could print these values starting at 0, incrementing by 50 and
ending at 200. Each is printed using a field width of 3.
>> for i = 0:50:200
fprintf('%3d\n',i)
end 09/13/2021 Defence univerisity,Collage of Engineering 79
What is the out put?
for i = 1:3
fprintf('I will not chew gum\n')
End
Ans
A function that is very useful with all types of plots is subplot, which
creates a matrix of plots in the current Figure Window.
Three arguments are passed to it in the form subplot(r,c,n),
Where
r and c are the dimensions of the matrix and
n is the number of the particular plot within this matrix.
The plots are numbered row wise, starting in the upper left corner. In
many cases, it is useful to create a subplot in a for loop so the loop
variable can iterate through the integers 1 through n.
When the subplot function is called in a loop, the first two arguments will
always be the same as they give the dimensions of the matrix. The third
argument will iterate through the numbers assigned to the elements of
the
matrix.
09/13/2021 Defence univerisity,Collage of Engineering 81
For example
in one Figure Window, between using 20 points and 40 points to plot sin(x)
between 0 and 2 * p. The subplot function creates a 1 x 2 row vector of plots in
the Figure Window, so that the two plots are shown side by side. The loop
variable
Iiterates through the values 1 and then 2.
WHILE LOOPS
The while statement is used as the conditional loop in MATLAB; it is used to
repeat an action when ahead of time it is not known how many times the action
will be repeated.
If statement
The general form of the if statement is
if expression
statements
elseif expression
statements
else
statements
end
For Loop
for I=n:m
statements
end
Questions ??