Department of Electrical Engineering
Electric Machines
Faculty Member: Dr. Syed Abdul Rahman Kashif
Dated:
20 September, 2016
Lab Engineer: Engr. Yasir Manzoor
Semester:
Fall, 2016
Lab Engineer: Engr. Noman Aslam
Session:
BSEE-14
LAB-1 Introduction to MATLAB
Name
Reg. No.
10 | P a g e
Report
Marks / 10
Viva
Marks / 5
Total / 15
1.1 MATLAB Interface
1.1.1 Step 1
Open MATLAB by clicking MATLAB.exe
1.1.2 Step 2
Click Desktop >> Desktop Layout >> Default
1.
2.
3.
4.
5.
Current folder
Command window
Workspace
Current folder
Start Button
Figure 1-1 Layout of MATLAB
11 | P a g e
1.2 MATLAB as Calculator (Basic Commands)
Figure 1-2 MATLAB Basic Trigonometric Function
Figure 1-3 MATLAB constants
1.2.1 Lab task 1
Use trigonometric functions to calculate sin, cos and tan of different angles (degrees and radians) and
comment on the result? (Hint Cosd)
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
1.3 Matrix Manipulation
1.3.1 Entering a Matrix:
1. Begin with square braket [
2. Separate element in a row with spaces.
3. Use semicolon (;) to separate rows.
4. End the matrix with another square bracket ]
1.3.1.1 Lab task 2
Creat a matrix having 3 rows and 3 coulmn and modify this varible thru workspace window to 4 X 3 matrix?
1.3.2 Matrix functions:
Figure 1-4 Matrix basic operations
12 | P a g e
Figure 1-5 Special Matrix commands in MATLAB
1.3.2.1 Lab task 3
A singular matrix is one whose inverse doesnt exist; using above matrix function, for matrix X and A
mentioned below determine
i.
ii.
Which matrix is singular?
________________________________________________________________________
Comments on determinant of matrix with respect to singular matrix?
________________________________________________________________________
________________________________________________________________________
X=
1.3.3 Matrix Arithematic:
A + B or B + A is valid if A and B are of the same size
A*B
is valid if As number of column equals Bs number of rows
A^2
is valid if A is square and equals A * A
Constant * A multiplies each element of A by constant.
1.3.3.1 Lab task 4
1. Using MATLAB, Claculate sum and product for above matrix X and A?
_______________________________________________________________________
2. X * A = A* X__________________________________________________(True/False)
Figure 1-6 Matrix operation in MATLAB
13 | P a g e
1.
2.
3.
4.
5.
To determine size of matrix
Transpose of matrix
Matrix Indexing:
Colon Operator:
To pic certain portion of matrix
>>
>>
>>
>>
>>
size(x)
x
x(i,j)
% i is row number and j is colom number
x = 0:1:10;
x(m:n,k:l )% specifies rows m to n and column k
to l.
6. To pic jth column of x
7. To pic ith row of x
8. Linear Spacing (row vector)
>> x(:,j)
>> x(i,:)
>> y = linspace (a,b)
>> y = linspace (a,b,n)
(a) start point
(b) end point
(n) no of divisions between a and b
>> theta = linspace (0, 2*pi , 101)
1.3.3.2 Lab Task 5
1. What is the difference in execution of command with semi colon at end, and without semicolon
at end of statement in MATLAB command window?
_____________________________________________________________________________________
_____________________________________________________________________________________
1.3.3.3 Lab Task 6
What is the difference in following commands?
>> y = linspace (0,10)
>> y = linspace (0,10,5)
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
1.3.3.4 Lab Task 7
You have provided following 5 X 5 matrix;
Write commands for following operations
1. To save 5th column in matrix a.
___________________________________________________
2. To pick element having value 20 ___________________________________________________
3. To extract main diagonal of matrix _________________________________________________
14 | P a g e
4. To extract
from matrix ___________________________________________________
1.4 Polynomial in MATLAB
Let
1. Finding roots
Roots_p1 = roots (p1)
2. Finding polynomial from roots
Poly (roots_p1)
3. Finding value of polynomial at any value
Polyval (p1, x)
4. Multiplication of two polynomial
Conv (a, b)
% multiplies two polynomials a and b
5. Division of two polynomials
[q,r]= edeconv(c,d) % divides polynomial c by polynomial d and displays
the quotient q and reminder r
1.4.1 Lab Task 8
1. Write command to create following polynomial in MATLAB in variable A;
______________________________________________________________________________________
2. Find polynomial having roots 5, 6, 3, 2?
______________________________________________________________________________
1.5 Differentiation & Integration
1.5.1 Differentiation:
>> diff(E) % Differentiates a symbolic expression E with respect to its free variable
as determined by find sym.
% Differentiates E with respect to symbolic variable v.
>> diff(E,v)
% Differentiates E n times for positive integer n.
>> diff(E,n)
>> diff(S,v,n) % Differentiates E n times with respect to symbolic variable v
1.5.1.1 Example:
>> syms p q
% two variables can be used in equations
>> y = 3*p^2 + 5*q^3 % y consists of p and q two variables
% differentiate y with respect to p only one time
>> diff(y,p)
>> diff(y,q,2) % differentiate y with respect to q twice
1.5.2 Integration
Indefinite integral of symbolic expression E with respect to its sym-bolic variable as defined by
find sym.
>> int (E)
% The int function, when applied to a symbolic expression,
provides a symbolic integration.
15 | P a g e
>> int (E,v)
% Indefinite integral of E with respect to scalar symbolic
variable v.
>> int (E,a,b)
>> int (E,v,a,b)
1.5.2.1 Example
>> int(y)
>> int(y,p,a,b)
% Definite integral of E with respect to its symbolic variable
form a to b, where a and bare each double or symbolic scalars.
% Definite integral of E with respect to v from a to b.
% a and b are lower and upper limits for definite
integrals
1.5.3 Lab Task 9
1. Differentiate the polynomial mentioned in task 8 part 1?
2. Integrate the result of above task?
1.6 System of linear Equations
System of linear equation is shown in figure 1-7.
Figure 1-7 System of linear equation
We can show it in matrix form as shown below
We can solve system of linear equation (value of x, y and z) by using following commands
>> A = [1 2 3; 4 5 6; 7 8 0];
>> B = [1; 1; 1]
>> X = inv(A)*b
Or
X = A\B
16 | P a g e
1.6.1 Lab Task 10
Find the values of x, y and z for system of linear equation mentioned below?
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
1.7 Plotting in MATLAB
1.7.1 Two dimensional plots
1.7.1.1 Method 1:
>> x=[1 2 3 8 6 3];
>> y=[2 3 5 6 7 9];
>> plot(x,y)
1.7.1.2 Method 2:
>>
>>
>>
>>
x=linspace(0,2*pi,60);
y=sin(x);
plot(x,y)
grid on
1.7.1.3 Method 3:
>> x=linspace(0,2*pi,60);
>> plot(x,sin(x))
1.7.1.4 Other useful commands:
>> Title(string)
>> Xlabel(string)
>> Ylabel(string)
>> Grid on
>> Grid off
>> Box on
>> Box off
1.7.2 Multiple Plot on same Axis
>>
>>
>>
>>
>>
17 | P a g e
Plot (x, y, x, u, x, v)
Plot (x, y,cms) % c is color code, m is marker type (*), s is line style (-)
x=linspace (0,2*pi,60);
plot(x,sin(x),'r',x,cos(x),'b',x,cos(x+20),'g')
grid on
Table 1-1 Styles, colors and markers used in MATLAB
1.7.3 Lab Task 11
1. Plot following trigonometric function on same graph having different axis for 0 to 360
degrees? Plots should have proper legends?
i. Sin,
ii. cos,
iii. tan,
iv. cot
2. Plot above functions with different color and marker on same graph/same axis for
above domain?
1.7.4 Three dimensional plots
1.7.4.1 3D line Plot:
plot3(x,y,z)
Example 1:
Example 2:( A Helix)
>> x=linspace(1,10,100);
>> t=linspace(0,10*pi);
>> y=linspace(3,50,100);
>> plot3(sin(t),cos(t),t)
>> z=linspace(6,80,100);
>> grid on
>> plot3(x,y,z)
1.7.4.2 Mesh Plot:
>> [x,y]= meshgrid(-10:0.01:10,-10:0.01:10);
>> z=x.^3+y.^2;
>> mesh(x,y,z)
1.7.4.2.1 Example
The first step in displaying a function of two variables, z = f (x; y), is to use the meshgrid function
to generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of
the function. The function can then be evaluated and graphed.
>> x = -8: .5: 8;
>> y=x;
>> [X, Y] = meshgrid (x, y);
>> R = sqrt (X.^2 + Y.^2) + eps;
>> Z = sin(R). /R;
18 | P a g e
>> mesh (x, y, Z)
1.7.4.3 Polar Plot
>> theta = 0: 0.2: 5*pi;
>> rho = theta. ^2;
>> polar (theta, rho, '*')
1.7.4.4 Sphere
>> sphere
>> axis equal
OR
>> [x,y,z] = sphere;
>> surf (x,y,z)
% sphere centered at origin
>> hold on
>> surf(x+3,y-2,z)
% sphere centered at (3,-2,0)
>> surf(x,y+1,z-3)
% sphere centered at (0,1,-3)
1.7.4.5 Lab Task 12
Draw plot between two variable x and y; both depends upon variable t as given below
=
Domain should be (-
) and
( )
) with more than 500 points.
Note: You can fill color using following command after plotting
>>fill (x,y,r)
1.8 Programming in MATLAB
So far in these lab sessions, all the commands were executed in the Command Window. The
problem is that; the commands entered in the Command Window cannot be saved and executed again
for several times. Therefore, a different way of executing repeatedly commands with MATLAB is:
to create a file with a list of commands,
save the file, and
Run the file.
If needed, corrections or changes can be made to the commands in the file. The files that are used
for this purpose are of two types
M-File Scripts
M-File Functions
1.8.1 M-File Scripts:
A script file is an external file that contains a sequence of MATLAB statements. Script files have a
filename extension .m and are often called M-files. M-files can be scripts that simply execute a series of
MATLAB statements,
1.8.1.1
Disadvantage:
Variables already existing in the workspace may be overwritten.
The execution of the script can be affected by the state variables in the
workspace.
19 | P a g e
1.8.2 M-File functions
Functions are programs (or routines) that accept input arguments and return output arguments.
Each M-file function (or function) has its own area of workspace, separated from the MATLAB base
workspace.
Table 1-2 Difference between scripts and functions
function f = factorial(n)
(1)
% FACTORIAL(N) returns the factorial of N.
(2)
% Compute a factorial value.
(3)
f = prod (1: n);
(4)
The first line of a function M-file starts with the keyword function. It gives the function name and order
of arguments. In the case of function factorial, there are up to one output argument and one input
argument.
In addition, it is important to note that function name must begin with a letter, and must be no longer
than the maximum of 63 characters to plot a saved function specify name and limits of x [min max]
1.8.2.1 Input and output arguments:
1.8.3 Input to script file:
There are three ways to take input in script file
i.
The variable is defined in the script file.
ii.
The variable is defined in the command prompt.
iii.
The variable is entered when the script is executed.
When the file is executed, the user is prompted to assign a value to the variable in the command
prompt. This is done by using the input command. Here is an example.
X= input (please enter value of x)
20 | P a g e
1.8.4 Output to command window
1.8.5 Control flow instructions
If . Else structure
1.8.6 Relational and Logical Operators
Figure 1-1-8 Relational and logical operators in MATLAB
1.8.7 For end loop
V states for any variable
S is start value V
I is increment in V
e is ending point of V
1.8.7.1 Example
For v = s: I: e
Statements
End
Example will print Yasir 5 times
1.8.8 While. end Loop
21 | P a g e
for I = 0: 2: 10
fprintf(yasir)
end
1.8.9 M File Script file Example
1.8.9.1.1 Step 1
Click on new script (top left corner)
Figure 1-9 Creating new script file in MATLAB
1.8.9.1.2 Step 2
You will have an empty editor to enter list of commands
Figure 1-10 MATLAB Editor
Write following temperature conversion program and save it.
22 | P a g e
%% temp conversion program
x=input('Please enter the temperature in Centigrade');
disp('the temp in kelvin is');
y=x+273
if y > 500
disp('Overloading')
else
disp('under loading')
end
Figure 1-11 Temp conversion program
1.8.9.1.3 Step 3
Now, press the green button to execute the program.
Figure 1-12 Program execution
In command window you will be prompt to enter temperature in centigrade.
23 | P a g e
Figure 1-13 Temperature conversion program
When you enter temperature in centigrade and press enter; Command window will show you value in
kelvin.
Figure 1-14 Temperature conversion program results
1.8.10 M File Function Example
Functions in MATLAB is written in same way as described above. Write following commands to build a
temp conversion function.
% temperature conversion function
function[k,avg]=temp_conv(x)
disp('the temp in kelvin is');
y=x+273
if y > 500
disp('Overloading')
else
disp('under load')
end
save it with name
temp_conv_func.m
1.8.10.1 how to call a MATLAB function?
You can call a function in command window by writing function name and argument to be pass
24 | P a g e
Figure 1-15 Function calling in MATLAB
Now, press enter to see the results
Figure 1-16 Function calling in MATLAB
You can use the function in any script file in same way.
1.8.11 Lab Task 13
1. Write a program to verify maximum power transfer theorem graphically? Program should
prompt to enter source impedance and range of load value? Hint:
25 | P a g e