Professional Documents
Culture Documents
Lab #1 Introduction To Matlab: Department of Electrical Engineering
Lab #1 Introduction To Matlab: Department of Electrical Engineering
Objectives
This Lab experiment has been designed to familiarize students with MATLAB and basic
understanding of MATLAB commands
File operations
Multiple windows view.
help, demos and example (Check whether this component is installed)
Wizard to create a GUI (graphical user interface)
Wizard to profile code
Toolboxes for different components like communication, control systems, data acquisition, curve fitting,
fuzzy logic, neural network etc. (These components may or may not be available, depending upon the
installation)
Command Window
Launch pad window (Toolbox Menu) Provide access to tools and demos
s=1+2
will result in the output shown below,
s=3
Here s is the variable having the integer value 3.
fun = sin(pi/4)
fun = 0.7071
In the second example the trigonometric function sine and the constant π are used. In MATLAB they are named sin
and pi, respectively. Note that the results of these computations are saved in variables whose names are chosen by
Variable name begins with a letter, followed by letters, numbers or underscores. MATLAB Release 2008 recognizes
only the first 63 characters of a variable name. To close MATLAB type exit in the Command Window and press
Enter or Return key. A second way to close your current MATLAB session is to select File in the MATLAB's
toolbar and next click on Exit MATLAB option. All unsaved information residing in the MATLAB Workspace
will be lost.
x_real = 10.01
x_real = 10.0100
is saved as a real number. Please note that x_int and x_real are variable names and do not define the type of
numbers.
Functions realmin and realmax return the smallest and the largest positive real numbers in MATLAB. For instance
typing realmin returns the minimum number that can be represented or saved in as a real number.
realmin
ans = 2.2251e-308
Complex numbers in MATLAB are represented in rectangular coordinate form. The imaginary unit -1 is denoted
either by i or j. Typing either i or j results in
i
ans = 0 + 1.0000i
In addition to classes of numbers mentioned above, MATLAB has three variables representing the non-numbers:
-Inf
Inf
NaN
help abs
Overloaded methods:
frd/abs
distributed/abs
iddata/abs
sym/abs
If you do not remember the exact name of a function you want to learn more about use command lookfor followed
by the incomplete name of a function in the Command Window. Now in the command window type help colon
To enter a statement that is too long to be typed in one line, use three periods, followed by
Enter or Return. For instance,
x = sin(1) - sin(2) + sin(3) - sin(4) + sin(5) -...
x= 0.7744
You can suppress output to the screen by adding a semicolon after the statement
u = 2 + 3;
x = sin( pi/5 );
cos( pi/5 ) %<--- assigned to what?
y = sqrt( 1 - x*x )
ans
On complex number, the basic operations are supported. Try the following:
z = 3 + 4i, w = -3 + 4j
real(z), imag(z)
abs([z,w]) %<-- Vector constructor
conj(z+w)
angle(z)
exp( j*pi )
exp(j*[ pi/4, 0, -pi/4 ])
MATLAB is an abbreviation for "matrix laboratory." While other programming languages mostly work with numbers
one at a time, MATLAB is designed to operate primarily on whole matrices and arrays. All MATLAB variables are
multidimensional arrays, no matter what type of data. A matrix is a two-dimensional array often used for linear
algebra.
Array Creation
To create an array with four elements in a single row, separate the elements with either a comma (,) or a space.
Colon Operator:
The colon alone, without start or end values, specifies all of the elements in that dimension. For example, select all
the columns in the third row of a:
a(3,:)
ans = 7 8 10
The colon operator also allows you to create an equally spaced vector of values using the more general form
start:step:end.
A = 0:10:100
A= 0 10 20 30 40 50 60 70 80 90 100
If you omit the middle step,as in start:end, MATLAB uses the default step value of 1.
(a) Make sure that you understand the colon notation. In particular, explain in words what the following
MATLAB code will produce
a=0:6
b = 2 : 4 : 17
c = 99 : -1 : 88
d = 2 : (1/9) : 4
e = pi * [ 0:0.1:2 ];
It will create 6 variables named a, b, c, d, and e. The variable a is a row vector with starting
value of 0 and ends at 6 with a default step size of 1 as there is no step size specified. It
contains 7 elements.
The variable b is also a row vector of four elements with starting value of 2 and ending
value 14 with a step size of 4. When it reaches 14 the next value is 18 which is greater than
the ending value specified so the array will be ended at 14.
The variable c is also a row vector. It starts from 99 and go in a descending manner to 88
due to step size of -1. If the ending value specified is greater than starting value with
negative step size, matlab will return empty array.
The variable d is a row vector of real numbers with starting value as 2.0000 and ending
value as 4.0000 with step size of 1/9. By default Matlab generate real numbers with 4 digits
after the decimal point however, it can be changed.
The variable e is also a row vector with starting value as 0 and ending value as 2*pi with
step size of 0.1*p. However, Matlab will not show the output because the output is
suppressed by the semicolon at the end.
(b) Extracting and/or inserting numbers into a vector is very easy to do. Consider the following definition
of f:
First let me explain this f. It generates a row vector of 12 elements where first three
elements are zeros defined by zeros function. Next 5 elements are equally spaced entries
between 0 and 1 generated by linspace function and last 4 elements are ones generated
by ones function.
f(4:6) uses the colon operator to extract the 4th , 5th and 6th element of array f. The colon
operator fetches data from first index all the way upto last index specified by the user.
In this expression first we have copied our f array in a new array and named it g so that our data in
f keep safe. In our g array which is exact copy of f, we have changed the 4 th, 5th and 6th elements with
the help of colon operator. We have replaced the 4 th, 5th and 6th elements of g array with pi, 2*pi,
and 3*pi respectively. Note that our f array will not be altered and now we have 2 different arrays.
To replace the even indexed elements of vector f, we will use following command:
f(2:2:length(f)) = pi^pi;
It will start from index 2 and ends at the total elements which is 12 in this case with step size of 2
and replace all even indexed elements with pi ^ pi. Note that this is similar to how we have created
g vector but this time we are making direct alterations in f vector.
cos is the built-in function in Matlab used to calculate cosines. This expression will create an array
of cosines of numbers ranging from 0 to 11*pi /4. It has created array due to the colon operator
used here. Colon operator will range numbers from 0 to 11*pi/4 and then cos function will take
cosine of each number and store it in h. h(1) is the first elements in h array and it is 1 because cos(0)
is 1. h(0) is not defined in Matlab. Opposed to other programming languages e.g. C++ where an
array starts with index 0, in Matlab all arrays starts with index 1. So asking for 0 index gives an
error in Matlab.
This 4 lines for loop can be easily implemented in a single line using colon operator. The alternative
and efficient way to create array using colon operator can accomplished using the following code:
g = cos((-5:5)*pi/3);
It will generate an array of 11 elements ranging from cos (-5*pi/3) to cos(-5*pi/3).
Explain why it is necessary to write g(k+6). What happens if you use g(k) instead?
It is necessary to write g(k+6) to start the indexing of array from 1. If we use g(k) instead then our
for loop starts from k=-5 and negative indexes are not allowed in Matlab. In Matlab indexes can
only start from 1 or any integer number except zero. So to make it 1 we have to use k+6 in the index
of g.
Plotting in MATLAB
Plotting is easy in MATLAB for both real and complex numbers. The basic plot command will plot a
vector y versus a vector x connecting successive points by straight lines. Try the following:
x = [-3 -1 0 1 3 ];
y = x.*x - 3*x;
plot( x, y )
z = x + y*sqrt(-1)
plot( z ) %<---- complex values: plot imag vs. real.
Note that both plots are similar. This is because the second plot is the plot of complex values
between their real and imaginary values. While the first plot is between two real values. But y has
the same values as the imaginary values in z. Therefore, both plots are similar.
Use help arith to learn how the operation xx.*xx works when xx is a vector; compare to matrix multiply.
In Matlab, there are two types of multiplication operators for vectors or arrays. One is simple * and
second one is .*. The * operator perform the vectors multiplication for which there is a condition
that the number of columns in first array should be equal to number of rows in second array (a
linear algebra multiplication). While .* operator multiples both arrays or vectors elements. Here we
Explain why the plot of real(y) is a sinusoid. What is its phase and amplitude?
The red line is the plot between real(y) and t. It is a sinusoidal function due to Euler’s formula
which is:
e ix =cosx +isinx
Functions in MATLAB
User-defined functions (i.e., those no pre-programmed in Matlab) can be defined by using an m file.
These files are simply text files whose name ends with the suffix .m. Those m files that a user may create
are typically stored in the work directory. This directory is the default working directory of a MATLAB
installation.
Here, function is a required MATLAB particle to identify the file as a function, assignment_variable(s) is
an optional dummy variable, function_name is the name given to the function, and arguments are optional
values passed on to the function from the main MATLAB interface or from within another function.
Suppose x1= [1 2 3 4 5 6 7 8 9] with index n1= 3:11 and x2= [2 4 6 8 10 12 14 16 18 20 22 24] with
index n2=1:12. Here you can observe that the length of both the signals is not same and the indexes of
both the signals are not starting from the same point. So you have to pad zeros before adding both the
sequences so that the output y will have the index values starting from 1 up to 12.
CODE:
Syntax of if/elseif/else
Best Resource or learning MATLAB: For getting familiar with MATLAB operations, matrices,
arrays, loops and plots etc., go to the link given below which contain official documentation on
mathworks with name “Getting Started with MATLAB”
www.mathworks.com/help/pdf_doc/matlab/getstart.pdf
https://www.tutorialspoint.com/matlab/
CONCLUSION:
In this lab, we have learned the introduction of one of the most popular programming languages for
linear algebra MATLAB. We have started with very basic introduction of variables, arrays, how to
create plots and then ended with making functions and scripts as .m files. We have created a
function which added two sequences even if their sizes and indices are different. After this lab, we
are able to code any basic program in MATLAB and are ready to take our learning to next level in
incoming labs.