MATLAB Introduction, Cheat Sheet of Law

The matlab computing environment and its capabilities for numeric computation and visualization. It covers the basics of working with complex numbers, plotting complex-valued functions, and performing vector and matrix operations in matlab. Examples and exercises to familiarize the user with matlab syntax and programming concepts. It is intended to prepare the reader for further labs and assignments in a course that utilizes matlab extensively. Topics such as evaluating complex expressions, plotting complex-valued functions, accessing and manipulating vectors and matrices, and creating custom matlab functions. It aims to remove some of the initial hurdles in learning matlab and enable the reader to effectively use it for signal processing, communication, and control tasks.

Typology: Cheat Sheet

2023/2024

Uploaded on 03/31/2024

daniyal-shabbir
daniyal-shabbir 🇵🇰

4 documents

1 / 18

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
EECS2602 – Winter 2015 Lab 1
Page 1
Laboratory Assignment 1
MATLAB Introduction
In this lab, you will be introduced to MATLAB by using it to evaluate expressions
containing complex numbers. Using MATLAB, you can easily express these complex
numbers in either rectangular or polar form. MATLAB’s plotting capabilities will be
introduced and used extensively. You will also use M-files and create some simple signal
processing functions that are used in later laboratory assignments.
1.1 OBJECTIVES
By the end of this laboratory assignment, you should be able to:
1. Use MATLAB to perform complex arithmetic.
2. Generate and plot signals and complex valued functions.
3. Confidently develop MATLAB M-files and save results of computations from a
MATLAB session.
1.2 REFERENCE
Review Topics:
1. Algebra of complex numbers
2. Sketching of discrete and continuous time signals
3. Vector and matrix algebra
1.3 INTRODUCTION
As you work through the problems and experiments in this course, you will be using
MATLAB - a powerful computing environment for numeric computation and
visualization - quite frequently. MATLAB is designed for ease of use and behaves as a
high-level programming language that is tailored for signal processing, communication,
and control tasks. It is used by professionals in industry and academia worldwide in
research, development, and design. An open source program having very similar
capabilities and commands is also available called Octave.
MATLAB, short for MATrix LABoratory, works on matrices of numbers. We focus
mostly on one-dimensional matrices called vectors that contain signal samples, or on
multiple-dimensional matrices containing several signals or the parameters of a system.
For example, a vector could contain just a list of values from a mathematical function that
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download MATLAB Introduction and more Cheat Sheet Law in PDF only on Docsity!

Laboratory Assignment 1

MATLAB Introduction

In this lab, you will be introduced to MATLAB by using it to evaluate expressions containing complex numbers. Using MATLAB, you can easily express these complex numbers in either rectangular or polar form. MATLAB’s plotting capabilities will be introduced and used extensively. You will also use M-files and create some simple signal processing functions that are used in later laboratory assignments.

1.1 OBJECTIVES

By the end of this laboratory assignment, you should be able to:

  1. Use MATLAB to perform complex arithmetic.
  2. Generate and plot signals and complex valued functions.
  3. Confidently develop MATLAB M-files and save results of computations from a MATLAB session.

1.2 REFERENCE

Review Topics:

  1. Algebra of complex numbers
  2. Sketching of discrete and continuous time signals
  3. Vector and matrix algebra

1.3 INTRODUCTION

As you work through the problems and experiments in this course, you will be using MATLAB - a powerful computing environment for numeric computation and visualization - quite frequently. MATLAB is designed for ease of use and behaves as a high-level programming language that is tailored for signal processing, communication, and control tasks. It is used by professionals in industry and academia worldwide in research, development, and design. An open source program having very similar capabilities and commands is also available called Octave. MATLAB, short for MATrix LABoratory, works on matrices of numbers. We focus mostly on one-dimensional matrices called vectors that contain signal samples, or on multiple-dimensional matrices containing several signals or the parameters of a system. For example, a vector could contain just a list of values from a mathematical function that

you wish to plot. We will first focus on familiarizing you with the matrix notation in MATLAB, and get you used to working with vectors and matrices in arithmetic operations. This introduction has three parts: reading, reading while doing, and doing guided by knowing expected results. Since the main difficulties in learning MATLAB are in learning the syntax and (in some cases) learning to program, we hope that this format will remove some of the trauma. Solutions to the questions in the “Quiz” section should be handed in as part of your Lab 1 report. This introduction is not intended to present you with everything you need to know about MATLAB; it is merely to bring you to a point where you can do the following labs in the course. Use the on-line help, and references for additional information. You should follow this text with MATLAB running, and work through the examples and questions. MATLAB is available on many other platforms. MATLAB runs under Microsoft Windows, Linux X Windows, or Mac OS. All versions of MATLAB are compatible in file storage format and M-file format, so data stored on one system can be transferred to another without loss. Each MATLAB session has at least two windows: a text window, where commands are typed and data is displayed, and a graphics window, where graphics appear. Octave has a virtually identical user interface to MATLAB. If you plan to do work at home on labs and assignments and do not have a license of MATLAB, it is recommended that you repeat some or all of the activities below using Octave on your home computer.

1.4 Tutorial, Part I

The following sections highlight some useful MATLAB commands by working through some example problems. You should work along with the text.

1.4.1 Start MATLAB

Find the MATLAB icon on the desktop and double click. Two windows will open. MATLAB has on-line help for all functions and a set of demos; we recommend that you try the demos so you can see some of MATLAB’s computing power and some of the functions available to you. When the text window opens, a prompt appears:

Other variables can be set in the same way:

z = 3+4*j z= 3.0000 + 4.0000i So, to set z to the solution of part b: z = (1-j)^ z= 0.0000 - 32.0000i

1.4.3 Plotting Complex-Valued Functions

Plots in MATLAB are generated using the plot function. plot (x, y) generates a plot where the values of the vector x indicate points along the horizontal axis corresponding to the values in the vector y that are to be plotted on the vertical axis. Vectors x and y must have the same number of elements. Since complex values have two components corresponding to a+jb, MATLAB provides the real and imag functions to separate the real and imaginary parts of an imaginary number:

z = 3+4*j; zr = real(z); zi = imag(z); real and imag break z into real and imaginary parts in the variables zr and zi, respectively. Note that typing a semicolon at the end of the command line prevents MATLAB from echoing the result back to your screen. This will be important when you create large matrices and vectors. In this example, the value of z was not printed as it was above. To plot a complex number, we can either plot the real parts vs. the imaginary parts or let MATLAB do it for us. Here, we supply zr and zi to the plot function: plot (zr,zi,’x’) and MATLAB generates a plot:

2 2. 2 2. 4 2. 6 2. 8 3 3. 2 3. 4 3. 6 3. 8 4 3

  1. 2
  2. 4
  3. 6
  4. 8 4
  5. 2
  6. 4
  7. 6
  8. 8 5 Figure 13.1 Example plot of a complex number The ‘x’ parameter to the plot function tells MATLAB to generate an x shape for each data point instead of a ‘connected-dot’ display. Since we only plotted one data point, this is extremely useful. In general you should always label axes on your plot and include a title. help plot shows you the other characters that can be used as well as the different colors that can be used on the plot. This plot would be exactly the same if we had entered:

plot(z,’x’) since the MATLAB default for plotting complex numbers is to plot the real parts on the horizontal axis and the imaginary parts on the vertical axis. Multiple sets of parameters can be given to plot; each pair of arguments is taken as x and y data pairs. If you wish to have several plots shown at once on different sets of axes, use subplot - see the on-line help - or open new figures by typing figure and creating a whole new plotting window.

with a 2x3 matrix is undefined. Matrix multiplication requires that the number of columns in the first matrix be the same as the number of rows in the second matrix. For example, multiplication of a 2x5 matrix A with a 5x3 matrix B results in a 2x3 matrix C=AB, whereas the multiplication BA is undefined. However, the multiplication D=B’A is defined, where ’ denotes the transpose operation in MATLAB.

1.5.1 Generating Complex Functions

Let’s generate values for the complex function f ( t )= 3 ej^3 π t for t ranging from 0 to 1 in 0.001 increments. The first step is to create a time variable; note the use of the : operator with a noninteger step size.

t = 0:0.001:1; Here the semicolon at the end is especially important, unless you really want to see and wait for all 1000 values to be echoed back on your screen. Next, construct a vector containing values of this function for each time value in t: f = 3exp(j3pit); It should be pointed out that transcendental functions (e.g. sin, cos, exp) in MATLAB work on a point-by-point basis; in the above command, the function exp computes a vector where each element is the exponential of its corresponding element in j3pi*t (1001 total elements).

1.5.2 Accessing Vectors and Matrices

The data in vectors can be viewed and displayed in several different ways: it can be plotted, printed to the screen, printed on paper, and saved electronically. It is not, however, always desirable to access the entire vector at once when displaying the information in it. To access single elements or ranges of a vector, an index element or list that identifies which elements are of interest is needed. Elements in MATLAB vectors are identified by the vector name and an integer number or index, much in the same way that DT signals are indexed by integer values. However, in MATLAB, only positive integer indices are used. Thus the first element in a row or column vector f is denoted by f (1), the second element by f(2), and so forth. To access specific elements in a vector, you need to use the name of the variable and the integer index numbers of the elements vector you wish to access. Range statements can be used for indices to access the indexed elements much in the same way that range statements are used to define vectors comprising values in a specified range. For example,

f(25);

f(3:10); f(1:2:50); The first line accesses the 25th element of f. The second accesses elements 3 through 10, inclusive; and the third statement returns the odd-numbered elements between 1 and 50. Elements in matrices require use of two-dimensional indices for identification and access. For example, f (3,2) returns the element in the third row, second column; ranges can also be used for any index. For example, f (1:3, 4:8) defines a matrix that is equivalent to a section of the matrix f containing the first, second, and third rows, and the fourth through eighth columns. If a : is used by itself, it refers to the entire range of that index. For example, a 3 x 5 matrix could have its fifth column referenced by f ( : , 5), which means “all rows, 5th column only,” as well as f (1:3, 5), which means rows 1 to 3, 5th column only. The index number can be another variable as well. This is useful for creating programming loops that execute the same operations on the elements of a matrix. From other computer programming experiences, you should be familiar with the idea of creating a loop to repeat the same task for different values. Here’s an example of how to do this using MATLAB. Suppose we want to generate an output vector where each element is the sum of the current element and the element from 10 back in an input vector. The task to be repeated is the sum of two elements; we need to repeat this for each element in the vector past 10. The elements of the vector x define the input ramp function to be integrated, y will hold the result, and k is the loop index: x = 3*(0:.1:5) + 2; y=zeros(size(x)); for k=11:length(x)

y(k)=x(k-10) + x(k); end

When a loop structure is entered in MATLAB, the body of the loop does not have a prompt printed; the command line acts the same as with a prompt. Note that the loop will not be executed until the end command is entered and followed by a carriage return. You will wait forever for the loop results if you leave off end (indicating to MATLAB that you have done all you wanted to in the loop). As you can see, the variable k is set to range from 11 to the length of x; this allows k to index all elements in x. k is set to increment by integers. Loops generally are not desirable, since they take a very long time to run. If possible, rewrite your operations in terms of vector additions and multiplications instead of

laboratory session.

1.6.1 Question 1

Add the functions ( ) ( )

2 3

p = 3 sin x + 2 cos y and ( )

2 q = 3 cos xy + 2 y for x in the range 0 to

  1. y = 0. 05 x + 2. 01 in all cases. Use increments of 0.01. Plot all three functions. Solution: This can be done in two different ways. The easiest way is to make two vectors containing the individual functions and a third vector containing the sum. The alternative is to algebraically substitute in x , y , p and q into the total expression and reduce. This is extremely unpleasant. Note that when a dot precedes an operator, as using .* for multiplication, it implies that each element in the vector (matrix) results from applying that operator to corresponding elements in the first and second vectors (matrices). For example, dot multiplication of two m x 1 vectors results in an m x 1 vector where each element is the product of the corresponding elements in the first and second vectors. Note that .* is equivalent to the “dot-product”, or inner product operation from linear algebra. This type of multiplication requires that the vectors (matrices) must be of the same size and is called pointwise, rather than vector or matrix, multiplication.

x = 0:0.01:5; y = .05x+2.01; p =3sin(x.x)+2cos(y.y.y); q=3cos(x.y) + 2y.y; z = p + q; plot (p); plot (q); plot(z);

  • (^50 100 200 300 400 500 )
  • 4
  • 3
  • 2
  • 1 0 1 2 3 4 Figure 1.4.1 Plot of p 0 100 200 300 400 500 600 5 6 7 8 9 10 11 12 13 Figure 1.4.2 Plot of q

1.6.3 Question 3

A polynomial function has roots at - 2, 2, - 2+3 j , - 2 - 3 j. Determine the polynomial, plot the four roots in the complex plane, and plot the polynomial function for the range x ∈(-5,5) in steps of 0.01. You may wish to use help to look up the functions poly, roots, residue and polyval. Answer: The polynomial is 4 9 16 52 4 3 2 x + x + xx − Figure 1.4.5 Roots of Problem 3 Figure 1.4.6 Plot of Problem 3

1.6.4 Question 4

The complex function f(t) has the form: f ( t ) = 3 ej^2 π^ t +^ π/^4. Plot the real and imaginary parts as a function of time from 0 to 3 seconds in 0.01-second increments. Also plot the magnitude and phase of f as a function of time. You may wish to look up the functions subplot, title, and plot to see how to generate more than one plot in the graphics window at the same time. You will also need abs and angle. These commands are very useful in signals and systems.

  • (^4) - 4 - 3 - 2 - 1 0 1 2 3 4
  • 3
  • 2
  • 1 0 1 2 3 4 - (^200) - 5 - 4 - 3 - 2 - 1 0 1 2 3 4 5 0 200 400 600 800 1000 1200 1400

Answer: Re( f(t)) : Im( f(t) ): Figure 1.4.7 Real and Imaginary plots Magnitude of f(t) : Phase of f(t) ): Figure 1.4.8 Magnitude and Phase plot

1.7 ASSIGNMENT PART II

This section will focus on the creation of MATLAB M-files. The solution to a problem is the M-file itself. We have provided you with the output of our M-file (without echoing the generation commands to the screen). This is done by using the command echo off at the beginning of the M-file.

  • (^80 0). 5 1 1. 5 2 2. 5 3
  • 6
  • 4
  • 2 0 2 4 6 8 - (^80 0). 5 1 1. 5 2 2. 5 3 - 6 - 4 - 2 0 2 4 6 8 - (^40 0). 5 1 1. 5 2 2. 5 3 - 2 0 2 4 (^00 0). 5 1 1. 5 2 2. 5 3 5 10

function to indicate to MATLAB that it is a function that may require inputs.

1.7.2 Question 5

Generate a file that calculates a sine wave of 5 Hz for 3 seconds using 0.001-second increments and plots the sine wave versus time with all axes labeled. Display the length of the time sample and the length of the sine wave calculated. Answer:

sine Length of time vector 3001

Length of sine vector 3001

  • (^10 0). 5 1 1. 5 2 2. 5 3
    1. 8
    1. 6
    1. 4
    1. 2 0
  1. 2
  2. 4
  3. 6
  4. 8 1 Figure 1.5.1 Solution to Question 5

1.7.3 Question 6

Generate a function called squarer that returns the vector with each element squared. Use this function with the sine wave from the previous problem and display the sum of the elements in both the sine wave vector and the vector composing square of the sine wave. Answer: the file prob5.m

prob Sum of sine

  1. 5372e- 14 Sum of sine squared 1.5000e+

Note that the sum of a sine squared should be 0.5 if we interpret the sum as an approximation to an integral. The function returns 1500 because there are 1000 samples per period and three periods. 1500 / 3000 is 0.5. You must be cautious when interpreting results because you are dealing with discrete elements in the vector instead of a true continuous function. Note also that if the sum of the sine function accurately approximates the integral, it should be 0. It is, instead, a very small number. This error is due to rounding errors in the least significant place of every sine value calculated and is an artifact of numerical computing. If you expect a sum to be equal to zero, don’t be surprised if it is very small instead of zero. A brief word about help: MATLAB’s help can be useful, but it can also be confusing. If you type help by itself, you will see a list of directories and a description of their contents. help will show you the contents of a directory; help gives you the help associated with the function. Sometimes these are cross- referenced, sometimes they aren’t.

1.8 Lab Problems

Submit solutions to the following problems with your lab write-up.

1.8.1 Problem 1

Compute ( )( ) ( 1 7 )( 3 2 )

j j j j

and express your answer in both rectangular and polar coordinates.

1.8.2 Problem 2

An interesting plot is generated by the complex function r = 1 −cos θ, where r is the radius of a complex number z expressed in polar coordinates and θ is the angle. Sweep θ from 0 to 2 π and plot the real and imaginary parts of z = r exp(jθ) as x and y coordinates, respectively.

1.8.3 Problem 3

In communications, a signal is called a power signal if it has a zero time average