Expt 1 - Matlab

Embed Size (px)

Citation preview

  • 7/30/2019 Expt 1 - Matlab

    1/19

    ELEC 2110 Experiment 1 1 of 19

    EXPERIMENT 1

    Introduction to MATLAB

    The objectives of this experiment are to:Learn to use MATLAB to create, format, analyze, and manipulate dataLearn to use MATLAB for plotting

    I. Introduction

    This laboratory experiment provides an introduction to the use of MATLAB.

    II. MATLAB Basics and Examples

    MATLAB is a commercial product of the MathWorks (http://www.mathworks.com), which is anindustry standard software tool in electromagnetics, signal processing, and control systems. A

    student version of MATLAB can be purchased at the Auburn University bookstore. The

    objective of this lab is to introduce the student to some of the basic features of MATLAB that are

    relevant to problem solving in the ECE department and engineering in general. You will receive

    additional MATLAB instruction in your other lecture courses.

    Access to software

    MATLAB is available on all of the computers on the engineering network and the computers in

    the laboratory. Students who wish to use MATLAB on their personal computers should

    purchase the Student Version of MATLAB.

    MATLAB Background and Tutorial

    The MATLAB program allows users to do many things that can be found in compiled

    programming languages, such as loops, if-then-else structures, and subroutines. The key

    differences between MATLAB and common programming languages such as C, C++, Java, or

    FORTRAN, are

    Declaringvariables - MATLAB does not require variables to be declared.

    Variable - the primary type ofMATLABTM variable is an array whose dimensions can be

    changed by the user at any time.

    Subroutines - For the most part, MATLABTM

    requires subroutine functions to be in separatefiles, each ending with .m. These are often calledm-files.

    Plotting - MATLABTM has a easy to use plotting function that can be used to plot several

    functions, add axis labels, legends, and print these plots for use in other documents.

    Trademark MathWorks

  • 7/30/2019 Expt 1 - Matlab

    2/19

    ELEC 2110 Experiment 1 2 of 19

    Linear Equations

    MATLABs most basic function is the solution of problems in linear algebra. One of the most

    common concepts in linear algebra is systems of linear equations. For example, suppose that we

    wish to solve for the unknownsx1

    andx2

    in the equations

    3x1 + 2 x2 = 7-3x1 x2 = -1

    The equations above are often written in matrix form.

    First: Define the vector of unknowns: x=

    x

    1

    x2

    .

    Then write the matrix form of the equation:

    3 2

    -3-1

    x

    1

    x2

    =

    7

    -1

    Notice that the rows of

    3 2

    -3-1are the coefficients of the unknowns x

    1andx

    2. This notation is

    important in the study of signals and systems, communications, electromagnetics, control

    systems, etc.

    Tutorial

    Start MATLAB on your machine. A user interface (Figure 1) will appear in which MATLAB

    commands can be entered with windows in which MATLAB programs and functions can be

    edited.

    Figure 1

    Variables

    MATLAB does not require that variables be declared. At the MATLAB prompt, enter the

    command:

  • 7/30/2019 Expt 1 - Matlab

    3/19

    ELEC 2110 Experiment 1 3 of 19

    a = 1

    You will see the output as shown in Figure 2. Notice that MATLAB prints back the result of this

    operation.

    Figure 2

    Now enter the commands

    b = 2

    c = a + b

    The values forb andc should be printed to the screen (Figure 3).

    Figure 3

  • 7/30/2019 Expt 1 - Matlab

    4/19

    ELEC 2110 Experiment 1 4 of 19

    Now enter

    d = a b;

    Notice the semicolon at the end of the command (Figure 4). The variable dwas calculated, but

    the semicolon instructs MATLAB not to print its value to the screen. You can see the value ofd

    by entering the command:

    d

    Figure 4

    Question 1(Write it in your report) Summarize the use of the semicolon in MATLAB.

    MATLAB variables can also be arrays or vectors. Type in the following commands andnotice the results:

    a = 1:4

    b = 4:8

    c = 1:2:9

    d = 1:3:10

    Check your results with Figure 5.

  • 7/30/2019 Expt 1 - Matlab

    5/19

    ELEC 2110 Experiment 1 5 of 19

    Figure 5

    Question 2(Write it in your report) Summarize the use of the colon in MATLAB.

    There are other ways to initialize variables.

    Question 3(Write it in your report) Enter the following commands. Summarize the use of the

    commands linspace, zeros, andones.

    f1 = linspace(0,1,5)

    f2 = linspace(1,2,9)

    g1 = zeros(1,4)g2 = zeros(3,4)

    h1 = ones(1,4)

    h2 = ones(4,2)

    You should get Figure 6.

  • 7/30/2019 Expt 1 - Matlab

    6/19

    ELEC 2110 Experiment 1 6 of 19

    Figure 6

    Finally, MATLAB also has string variables, which are always set off with single quote marks.message = hi there

    In MATLAB, you will see Figure 7.

    Figure 7

  • 7/30/2019 Expt 1 - Matlab

    7/19

    ELEC 2110 Experiment 1 7 of 19

    Notice that variable names follow the same rules as in other programming languages: they must

    start with a letter, and otherwise may be composed of any letters, numbers, or the underscore

    character _. For example,

    elec2010today = a great class

    is a legal statement in MATLAB.

    Calculations

    MATLAB can also perform math operations on array/vector variables.

    Question 4(Write it in your report) Enter the following commands and summarize the results

    for your report.( We have already saved the values of a, b, c, d into MATLAB, when ?)

    w = a + d

    x = b + c

    y = a + c

    You should get the results in Figure 8. The last command gives you an error. Why?

    Figure 8

  • 7/30/2019 Expt 1 - Matlab

    8/19

    ELEC 2110 Experiment 1 8 of 19

    MATLAB does allow math operations with scalars even if dimensions dont match. Enter the

    following command (Figure 9):

    z = a + 4

    Figure 9

    Linear algebra problems

    Since MATLAB naturally works with matrices and vectors, the system of equations mentioned

    earlier can be solved very easily in MATLAB. Enter the following commands in MATLAB:

    A = [ 3 , 2 ; -3 , 1]

    B = [ 7 ; -1 ]

    x = A\B

    check = A*x - B

    MATLAB will give you the result in Figure 10.

    Figure 10

  • 7/30/2019 Expt 1 - Matlab

    9/19

    ELEC 2110 Experiment 1 9 of 19

    Notice how matrices and vectors are entered: entries on rows are separated by (optional) commas

    and each row ends with a semicolon. While the commas are optional, they are a good idea, as

    are parentheses. Notice the line x = A\B. This line performs the operationx=A-1

    B; that is, it

    computes the solution ofAx=B.

    Question 5 (Write it in your report) Enter the following commands and write yourobservations. Notice that the commas and blanks in each line do make a difference in the result.

    x = [ 1, - 2 ]

    y = [ 1 - 2 ]

    z = [ 1 -2 ]

    You can see the difference from what you get (Figure 11).

    Figure 11

    (It is a good idea to use commas and parentheses in order to be sure that MATLAB correctly

    interprets your commands.)

  • 7/30/2019 Expt 1 - Matlab

    10/19

    ELEC 2110 Experiment 1 10 of 19

    Loops

    MATLAB has loop capabilities like C, C++, etc. However, the syntax for loops in MATLAB is

    different. The syntax is:

    for varname = row_vector

    loop commands go hereend

    For example, type in the following commands:

    for x = 1:5

    thisvar = [x, x^2]

    end

    You should get a table of powers of two (Figure 12). We illustrate loops further in the next

    section.

    Figure 12

  • 7/30/2019 Expt 1 - Matlab

    11/19

    ELEC 2110 Experiment 1 11 of 19

    Displaying and output

    MATLAB can display variables to the screen using the fprintf command, which is similar to

    the C commands printf andfprintf. Enter the following commands at the MATLAB

    window:

    f1 = linspace(0,1,5)for myvar = f1

    fprintf(the value is %e\n, myvar);

    end

    MATLAB will return Figure 13.

    Figure 13

    Notice that the variable myvar takes each value in the row vectorf1 (or a below). The

    tag %e indicates that the value is a number that should be printed in exponential format. If the

    values are integers, you can also use the %d tag:

    a = 1:4

    for myvar = a

    fprintf(the value is %d\n,myvar);

    end

    Check the difference between these two types (Figure 14).

  • 7/30/2019 Expt 1 - Matlab

    12/19

    ELEC 2110 Experiment 1 12 of 19

    Figure 14

    MATLAB also has if-then-else commands. Type in this example (Figure 15):

    for myvar = 1:6

    if( myvar < 4 )

    fprintf(%d is less than 4\n,myvar);

    elseif ( myvar == 4 )

    fprintf(%d is equal to 4\n,myvar);

    else

    fprintf(%d is greater than 4\n,myvar);

    endend

    Figure 15

  • 7/30/2019 Expt 1 - Matlab

    13/19

    ELEC 2110 Experiment 1 13 of 19

    M-files

    By now youve noticed that typing in commands in the MATLAB command window can be

    tedious. MATLAB allows you to write scripts (programs) calledm-files so that you can write

    commands in a separate text file and the run them later.

    Use the MATLAB editor (file -> new -> m-file or click ) to open a new m-file. Enter thesecommands in the file: (You will see Figure 16 after you open a new m-file).

    Figure 16

    M-file 1 myloop.m

    for myvar = 1:6

    if( myvar < 4 )

    fprintf('%d is less than 4\n',myvar);

    elseif ( myvar == 4 )

    fprintf('%d is equal to 4\n',myvar);

    else

    fprintf('%d is greater than 4\n',myvar);end

    end

    It should be the same as Figure 17.

  • 7/30/2019 Expt 1 - Matlab

    14/19

    ELEC 2110 Experiment 1 14 of 19

    Figure 17

    Save the file as myloop.m. (See Figure 18.)

    Figure 18

    Notice that MATLAB does not run these commands. Now, in the MATLAB command window,

    type in

    myloop

    You should get Figure 19.

  • 7/30/2019 Expt 1 - Matlab

    15/19

    ELEC 2110 Experiment 1 15 of 19

    Figure 19

    Notice that you do nottype in the .m at the end of the command.

    m-files can be called from other m-files. Write the following commands and save them in

    myfile.m.

    M-file 2 myfile.m

    fprintf('Hi there.\n');

    myloop

    fprintf('back from myloop\n');

    At the MATLAB command prompt, type in

    myfile

    and observe what MATLAB does.

    Plotting

    One of the most useful features of MATLAB is its plotting capability. Enter the following

    commands in the MATLAB command window, and write what happens as each command is

    executed.

    t = linspace(0,10,100);

    x = exp(-t);

    plot(t,x);xlabel(time (s));

    ylabel(x(t));

    title(plot of e^{-t});

    grid on

    The output should be Figure 20.

  • 7/30/2019 Expt 1 - Matlab

    16/19

    ELEC 2110 Experiment 1 16 of 19

    Figure 20

    More than one signal can be plotted at a time. Enter the following commands in the MATLAB

    command window:

    y = sin(t);

    plot(t,x,-, t,y,-.);

    legend(x(t)=exp(-t), y(t) = sin(t));

    grid on

    xlabel(time (s));

    title(two plots at once)You can see the two signals in one plot (Figure 21).

  • 7/30/2019 Expt 1 - Matlab

    17/19

    ELEC 2110 Experiment 1 17 of 19

    Figure 21

    Notice that each plot has three arguments: thex axis values, they axis values, and a string for the

    line style. Other plotting options are documented in MATLABs help files. Type in help

    command_name to see on-line documentation. For example,

    help plot

    and you will see Figure 22.

  • 7/30/2019 Expt 1 - Matlab

    18/19

    ELEC 2110 Experiment 1 18 of 19

    Figure 22

    Functions

    A function is an m-file that follows a special format. Enter the following text into an m-file

    window and save it as tempC.m.

    M-file 3 tempC.m

    function tempDegC = tempC(tempDegF)

    tempDegC = (tempDegF-32.0)/1.8;

    Now type in the following command at the MATLAB prompt

    bodyTemp = tempC(98.6)

    Your output should be like that shown Figure 23.

  • 7/30/2019 Expt 1 - Matlab

    19/19

    ELEC 2110 E i 1 19 f 19

    Figure 23

    Question 6(Write it in your report) What is the value ofbodyTemp?

    Remark 4 Notice the function tempC does not have a return statement or an end statement.

    It only requires that the return variable centigrade be defined somewhere in the file.

    Remark 5 Important! Notice that the name of the function, tempC, matches the name of the

    file, tempC.m. MATLAB requires this convention. This means that every function must be in

    its own m-file.

    II. EXERCISES

    [1] Create an array for theta varying from 0 to 2 containing at least 20 points. Now plot thesine and cosine functions, both on the same plot as a function of theta, with the grid turned on.

    Add appropriate labels and title to the plot. Include this plot in your report. Make a second plot

    of the sine and cosine functions as a function of degrees instead of radians and include in your

    report.

    [2] Given the following temperatures in Fahrenheit, convert them to Centigrade, Kelvin and

    Rankine using MATLAB. How are the answers different? Now format them to get 2 decimal

    places in both cases and compare your final answers.

    -148, 14, 32, 50, 212, 572

    [3] Create a plot of the function V = R I for the values ofR = 100 ohms andI = 0 to 100

    amperes using at least 12 values ofI. Add labels and a title to your plot and include it in your

    report.

    [4] Create a plot of i(t) = 10 - 40 e-t

    amperes for the values of t = 0 to 10 seconds with

    increments of 0.5 seconds. Determine the value of time at which i(t) = 0 from your plot. Also,

    determine the maximum value of i(t) from the your plot. Add labels and a title to your plot and

    include it in your report.