Vous êtes sur la page 1sur 12

EELE 201 Circuits 1

Introduction To MATLAB
1.1 Introduction MATLAB from MathWorks, Inc. is a powerful and flexible programming tool for carrying out a variety of mathematical analyses. The name MATLAB is derived from MATrix LABoratory, reflecting the fact that MATLAB is particularly well-suited for carrying out operations on matricies. You will learn more about the power of matrix analysis by taking M221. For now, the goal of this chapter is simply to introduce you to MATLAB and thus allow you to carry out some rather straightforward math and graphing tasks with it. Only slightly more than the bare minimum for using MATLAB is described herein. Be certain to experiment on your own and to search the WEB for sites that have MATLAB tutorials. As another resource for those of you interested in learning more about MATLAB than these few pages reveal, consider purchasing The current text required in more advanced EE classes at MSU. It is recommended that you have some type of electronic storage media (whether it be your Z:\ drive space or a simple flash drive) available as you go through this tutorial. NOTATION FOR THE TUTORIAL: >> command Indicates a command line prompt (do not type the >> symbol) Text written in courier font, indicates commands to be typed. Press the enter key after each command line

To open MATLAB on a windows-based PC: Start All Programs MATLAB 7 (or Latest Version available) MATLAB 7 Or, if available on the desktop, double click the MATLAB 7 icon

Within the MATLAB desktop are the command window, the launch pad and the command history windows. We will do our programming in the command window or in

EELE 201 Circuits 1

a separate script file to be discussed later. The launch pad lists the various MATLAB toolboxes that are available on the computer network. Finally, the command history window keeps track of all the keystrokes that are entered in the command window and thus may be used as a handy reference for recalling what you have typed. 1.2 Making simple calculations MATLAB may be used as a calculator. For example, lets say we want to calculate:

43 8 . 6
In the MATLAB command window, one might type the following line and press the enter key. >> (4-3)/6*8

In doing so MATLAB gives the following result (stored under the variable ans). ans = 1.33333333333333 While MATLAB follows the standard order of operations, for enhanced clarity one could include an additional set of parenthesis to clarify the equation. For example >> ((4-3)/6)*8 ans = 1.33333333333333 As expected, the two forms of the equation are equivalent. In addition to the example shown above, one may perform the standard set of arithmetic operations. Table I below lists the standard operations and their corresponding MATLAB text. TABLE I Operation Example MATLAB MATLAB Symbol command Addition A+B + A+B Subtraction A-B A-B Multiplication AB * A*B Division AB / A/B B Exponentiation A ^ A^B 1.3 Assigning a set of numbers to a variable

EELE 201 Circuits 1

One of the greatest strengths of MATLAB is it ability to quickly run a series of calculations on a set of numbers with a minimal command structure. Below is an example in which we will use two methods to create a set of numbers from 0 to 10 in steps of 1.
Method 1: Create the number set through entering each number individually.

We will store the number set in the variable A. At the prompt (>>) in the command window, type the following with each number separated by a space, a comma or a comma followed by a space (recall that you are not to type >>): >> A = [0 1 2 3 4 5 6 7 8 9 10] You should see:

We have created a set of numbers from 0 to 10 (in steps of 1) and stored them in the variable A. The results have been displayed. Now type the up arrow () once. You should see the command line that you just typed. In fact, one my cycle through previous commands by using the up arrow key.

Lets slightly modify the line by adding a semicolon to the end of the line. Add the semicolon to the end of the line and press enter. You should see:

EELE 201 Circuits 1

Thus, if you use a semicolon after a particular command line, the results of the command will not be displayed. However, the results are still stored in memory. To verify this, at the command line type >> A You should see:

NOTE: Instead of using spaces between the numbers, we could have elected to separate the numbers using a comma or a comma and a space. Method 2: Create the number set through entering a starting number, a step (i.e. increment), and the ending number.

At the prompt in the command line, type (no spaces are required) >> B=0:1:10 You should see:

EELE 201 Circuits 1

In this case, the number set has been stored under the variable B and was created by entering the initial number (0), the desired increment (1) and the final number (10). Clearly, this second method is preferred when entering a large set of regularly ordered numbers. Recall that if we had placed a semicolon at the end of the command line, the results would have been stored but not displayed. At this point, it is important to distinguish between scalar, array, vector and matrix insofar as MATLAB is concerned. SCALAR: A single number ARRAY: A collection of numbers VECTOR: A collection of numbers arranged in either a single column or a single row MATRIX: A two dimensional array which can consist of multiple rows and/or columns.
1.4 Performing simple arithmetic operations on a set of numbers Lets create a new set of numbers, stored in the variable C, by multiplying each element of A by the number 6.

>> C=6*A; Verify that indeed the variable C contains the correct values. In the above operation, we multiply a row vector (A consists of a single row with 11 columns) by a scalar (6) to create a second row vector C. Both A and C should have the same size. Lets check. >> size(A) ans = 1 11 >> size(C) ans = 1 11 Both A and C have a size of 1 11. This means that both consist of a single row with 11 columns (the size command returns the number of rows followed by the number of columns). Lets change A from a row vector to a column vector using the transpose command (), assign the transposed vector to D and check its size. >> D=A'; >> size(D) ans = 5

EELE 201 Circuits 1

11

The transpose was successful we created a column vector with 11 rows. OK, so we have seen scalars and vectors, what about matricies? Enter the following in the MATLAB command window taking care to use a semicolon after the number 8. >> E=[0,1,4,-8;4,2,10,-15] E= 0 4 1 4 -8 2 10 -15
<ENTER>

E is neither a scalar nor a simple vector; rather, it is a matrix. What is its size? Use MATLAB to verify your answer. So to reiterate: a scalar is a single number, an array is a collections of numbers, a vector is an array with either a single column or a single row, and a matrix is an array that may consist of multiple rows and/or columns. Why do we care?
TABLE II: ELEMENT-BY-ELEMENT OPERATIONS Operation Example MATLAB MATLAB Symbol command Addition of a scalar to A+b + A+b an array Subtraction of a scalar A-b A-b from an array Addition of arrays A+B + A+B Subtraction of arrays A-B A-B Multiplication of an Ab * A*b array by a scalar Division of an array by Ab / A/b a scalar Multiplication of AB .* A.*B arrays Division of arrays AB ./ A./B Scalar Exponentiation Ab ^ A^b B Array Exponentiation A .^ A.^B

Later in the course we will solve for the voltages and currents in an electrical circuit by assembling a set of equations that conform quite nicely into matrix form. We may then use MATLAB to solve the matrix-based system of equations by entering a few commands. In other instances, we will find opportunity to use scalars and vectors. Depending on the circumstance, we may either want to carry out multiplication or division operations in which the operation is performed on in an element-by-element 6

EELE 201 Circuits 1

manner or, we may desire to use the rules of matrix algebra which conform to a different set of patterns that you will learn in subsequent math courses. When using MATLAB, we must be careful to write our code so as to inform MATLAB which type of operation that we desire. Table II provides a list of common element-by-element operations. In the table, a capital letter corresponds to an array and a lowercase letter corresponds to a scalar. Lets try a couple of examples. Recall that you have defined row vectors A and B, a column vector D and a 2x4 matrix E. You may use the who command to obtain a list of the variables which are currently in memory. The whos command goes a step further and lists both the variables currently in memory and their respective sizes. If you have followed this tutorial, the whos command should reveal the following. >> whos Name Size A B C D E 1x11 1x11 1x11 11x1 2x4
<ENTER> Bytes Class

88 88 88 88 64

double array double array double array double array double array

Grand total is 52 elements using 416 bytes Lets introduce a scalar and proceed with a few examples. >> F=3;
>> A*F ans = 0 3 6 9 12 15 18 21 24 27 30

Thus A*F simply multiplies each element of A by the scalar F. >> A.*B ans = 0 1 4 9 16 25 36 49 64 81 100

Thus A.*B multiplies each element of A by the corresponding element in B (e.g. Aij*Bij, where i refers to the row number and j to the column number).

EELE 201 Circuits 1

>> C.*D ??? Error using ==> .* Matrix dimensions must agree. The attempted element-by-element multiplication of vectors C and D failed with MATLAB responding that the Matrix dimension must agree. (Note: A vector is a simple case of a matrix in which there is only one row or one column.) A quick check using either the size command or the whos command reveals that C is a 1x11 vector and D is a 11x1 vector. To make the element-by-element multiplication work, we must transpose one of the vectors. For example, >> C.*D' ans = 0 6 24 54 96 150 216 294 384 486 600

In the following command, the matrix E is divided by a second matrix. The second matrix is simply the E matrix with the value 4 being added to each of its elements. >> G=E./(E+4) G= Columns 1 through 3 0 0.20000000000000 0.50000000000000 0.50000000000000 0.33333333333333 0.71428571428571 Column 4 2.00000000000000 1.36363636363636 While having MATLAB compute with many significant figures is often desirable, viewing more compact results is typically more convenient. Try the following. >> format short >> G G= 0 0.2000 0.5000 2.0000 0.5000 0.3333 0.7143 1.3636

EELE 201 Circuits 1

Or, >> format bank >> G G= 0 0.50 0.20 0.33 0.50 0.71 2.00 1.36

1.5 Using MATLAB For Plotting

MATLAB has the ability to create a variety of graphs. For example, lets say that we want to plot the function y=x2 for values of x that range from 3 to 3 in steps of 0.1. We could enter the following commands in MATLAB. >> x=[-3:0.1:3]; >> y=x.^2; >> plot(x,y) In doing so, a new window should pop up which displays the following figure.

Figures without relevant titles and properly identified axes are often of little use. In the following command set, we introduce a second function (y=x3) and, using the hold function, plot it on the same graph as y=x2. In addition, we increase the linewidths of the curves, add a title, axes labels, and a legend. While the colors of the traces are blue (the default) and red (our choice for the second plot), adding various line types is particularly helpful when printing graph on a standard grayscale printer. 9

EELE 201 Circuits 1

>> plot(x,y,'linewidth',3) >> hold Current plot held >> z=x.^3; >> plot(x,z,'r--','linewidth',3) >> title('Squared Versus Cubed Functions','Fontsize',20) >> xlabel('X Values','Fontsize',20) >> ylabel('Y Values','Fontsize',20) >> legend('Squared Function','Cubed Function') Below is the resulting figure.

Further editing of a figure may be accomplished either in the command window or in the figure window. For example, increasing the fontsize of the legend and placing it elsewhere in the graph would improve the readability of the figure. For further information on specifying the properties of lines, use the MATLAB help index and search under linespec. That is, from the command or main windows Help MATLAB Help, select the index tab and type linespec
1.5 Creating and Running M-Files

When writing a long set of command lines, or in generating a routine that you would like to use at a later date, it is helpful to create a so-called M-File or script. Such files 10

EELE 201 Circuits 1

may be saved, modified and run within the MATLAB environment. To create an M-File, from the main window of MATLAB File New M-File Simply type the succession of commands that are to be carried out. You may create a non-executing comment line by beginning the line with a percent symbol (%). Below is a MATLAB script for plotting sine and cosine functions over two periods.

% This M-file contains a simple routine to plot sine and cosine functions % over two periods. % Creation of a vector consisting of two periods (720 degrees) of a sinusoid in steps of 1 % degree. (Note: MATLAB understands pi to be 3.14159265. MATLAB assumes the % argument of a sinusoid to be in radians, thus the pi/180 factor.) x=[0:1*pi/180:720*pi/180]; % Sine and cosine functions y1=sin(x); y2=cos(x); % Generating the desired waveforms. Note that radians have been converted back to % degrees for the plot. plot(x*180/pi,y1,'linewidth',3) title('Sine and Cosine Functions','Fontsize',20) hold plot(x*180/pi,y2,'r--','linewidth',3) xlabel('Degrees','fontsize',20) ylabel('Sine/Cosine Values','fontsize',20) legend('Sin(x)','Cos(x)') hold off % "hold off" command has been included in order to refresh the figure % window should one wish to run the program more than once Once you have created such a script, save the program to the desired location. You may run the script from the script window by selecting Debug Run (or by just pressing the F5 key) If your M-File has not been saved in the present working directory for MATLAB, you will see the following:

11

EELE 201 Circuits 1

Simply select OK to have MATLAB change its current directly appropriately. The following figure was generated using the script given above. (Note: The legend was resized and moved using the editing capabilities in the Figure window.

If there are any errors in your code that cause a MATLAB error, they will be described in the command window. You may then alter your script file appropriately.
Remember to use the help options in MATLAB and consult tutorials on the web.

12

Vous aimerez peut-être aussi