Ch 3 Script M-Files

  • View
    218

  • Download
    0

Embed Size (px)

Citation preview

  • 7/29/2019 Ch 3 Script M-Files

    1/40

    MATLABfor Scientists and Engineers

    Numerical Computing

    with .

    Byoung-Jo CHOI, PhDUniversity of Incheon

  • 7/29/2019 Ch 3 Script M-Files

    2/40

    References

    MATLAB Getting Started Guide, MathWorks

    MATLAB User's Guide, MathWorks

    Mastering MATLAB 7, Duane Hanselman and Bruce Littlefield,

    Pearson/Prentice Hall, 2005

    Numerical Computing with MATLAB, Cleve Moler, MathWorks MATLAB7,, 2009

    MATLAB: An Introduction with Applications, Amos Gilat, John Wiley

    & Sons, Inc., 2004

    Graphics and GUIs with MATLAB, 3rd Ed, Patrick Marchand and O.Thomas Holland, Chapman & Hall/CRC, 2003

    2

  • 7/29/2019 Ch 3 Script M-Files

    3/40

    Script M-Files

    Numerical Computing

    with .

    MATLABfor Scientists and Engineers

  • 7/29/2019 Ch 3 Script M-Files

    4/40

    You will be able to

    Write simple scriptm-files using the editor, Get userinputs and print the formatted results,

    Give explanations on your scripts using

    comments,

    Use cell mode for efficient coding and evaluation,

    Create a simple dialoguewindow,

    Save and Load data to/from MATLAB data file,

    text file as well as Excel files

    Use timerto perform repeated action

    4

  • 7/29/2019 Ch 3 Script M-Files

    5/40

    What is Script M-File

    Text file comprised of a series of MATLABcommands

    The file name ends with .m, hence m-file.

    MATLAB interprets the lines in a script m-file. Example

    5

    calc_price.m

    1:2:3:4:5:

    % Calculate the total pricenItem = input('Enter the number of items:');uPrice = input('Enter the unit price:');tPrice = nItem * uPrice;fprintf('The total price is %d.\n', tPrice );

  • 7/29/2019 Ch 3 Script M-Files

    6/40

    Launching M-File Editor 1/3

    'New M-File' Toolbar

    6

    Using Toolbar

  • 7/29/2019 Ch 3 Script M-Files

    7/40

    Launching M-File Editor 2/3

    'File

    New

    M-File' Menubar

    7

    Using Menubar

  • 7/29/2019 Ch 3 Script M-Files

    8/40

    Launching M-File Editor 3/3

    From Command History Window Create m-file using the past commands

    8

    Popup Menu

  • 7/29/2019 Ch 3 Script M-Files

    9/40

    Save and Run the Script

    F5 to save the changes andrun the entire script.

    9

    Run All

    Save

    Modified butNot Saved Yet!*

    F5

  • 7/29/2019 Ch 3 Script M-Files

    10/40

    Evaluate the Selected Script

    F9 to run the selected script. Menubar: Text Evaluate Section

    10

    F9 to Run the Selection Using Hot Key

  • 7/29/2019 Ch 3 Script M-Files

    11/40

    Useful Functions for Scripts

    For User Interactions

    11

    beep

    Echo MATLAB commands in scripts.echo on

    echo off Act silently. Default mode.

    price = input('Enter the Unit Price: ');

    fprintf('The price is %d.\n', price * 20 );

    name = input('Enter your name: ','s');

    disp(name);string input

    number input

    pause pause(5) sec waitforbuttonpress

    keyboard Gives control to keyboard.

    Go into k>> mode

    Type R-E-T-U-R-N (5 characters) to exit.

    Debug Mode

  • 7/29/2019 Ch 3 Script M-Files

    12/40

    Getting User Inputs 1/2

    Getting user input from command line

    12

    greetings_input.m

    % Get user inputs using command line

    name = input('Your name: ','s');

    age = input('Your age: ');

    fprintf( ['Hello, %s!' ...' You will be %d years old next year\n'], ...

    name, age+1);

    %%

    fprintf( 'Press key to continue..');

    pausetoday1 = date;

    fprintf( '\nToday is %s.\n', today1 );

  • 7/29/2019 Ch 3 Script M-Files

    13/40

    Getting User Inputs 2/2

    Getting user input from dialog box

    13

    greetings_dlg.m

    %% Get user inputs using dialog

    prompt = {'Your name', 'Your age:'};

    dlg_title = 'Greetings';

    num_lines = 1;def = {'Sam','21'};

    answer = inputdlg (prompt,dlg_title,num_lines,def);

    name = answer{1};

    age = str2num (answer{2});

    msg = sprintf( 'Hello, %s! You will be %d years old

    next year\n', name, age+1);h = msgbox (msg, 'Greetings');

    uiwait (h)

    today1 = date;

    msg = sprintf( '\nToday is %s.\n', today1 );

    h = msgbox (msg, 'Greetings');

  • 7/29/2019 Ch 3 Script M-Files

    14/40

    Other Dialog Boxes

    14various_dlgs.m

    warndlg

    errordlg helpdlg

    questdlg

    listdlg

  • 7/29/2019 Ch 3 Script M-Files

    15/40

    Comments

    Line comments

    Block comments

    15

    % This m-file demonstrates filtering operation% of FIR designed for removing a tone noise.% Refer to Book1 for the exact algorithm% Three 2-R plot will be drawn.

    %{This m-file demonstrates filtering operation

    of FIR designed for removing a tone noise.Refer to Book1 for the exact algorithm}%

    Useful for commenting out a block of code

    temporarily for debugging.

  • 7/29/2019 Ch 3 Script M-Files

    16/40

    Commenting Out

    Ctrl+R for commenting out the selection Ctrl+T for un-commenting out the selection

    16

  • 7/29/2019 Ch 3 Script M-Files

    17/40

    Code Cells

    Code blocks separated by %%

    17

    %% Initializing Data Structure

    Fs = 1440; % Sampling frequency

    Ts = 1 / Fs; % Sampling Time

    F0 = 2.4e3; % Carrier frequency

    %% Generate Time Domain Signal

    t = 0:Ts:2;

    s = sin(2*pi*F0*t);

    %% Plot the Signalplot(t,s);

    Code Cell 3

    Code Cell 1

    Code Cell 2

  • 7/29/2019 Ch 3 Script M-Files

    18/40

    Enabling Cell Mode

    When enabled, cell control toolbar appears.

    18

  • 7/29/2019 Ch 3 Script M-Files

    19/40

    Evaluating the Cells

    Run / Run & Go

    19

    Evaluate the current cell.

    Evaluate the cell and advance to the next cell.

    Ctrl Enter+

    Ctrl Shift+ Enter+

  • 7/29/2019 Ch 3 Script M-Files

    20/40

    Modify Parameter and Run the Cell

    Increment / decrement a parameter by Multiply / divide a parameter by

    20

    Change the value near the

    cursor and execute the cell.

    plot_cosine.m

  • 7/29/2019 Ch 3 Script M-Files

    21/40

    Output Commands - disp

    disp

    21

    disp(name of a variable) ordisp('text as string')

    disp_demo.m

    n = [8 1 6]

    disp(n) % show the values of ndisp('Magic Numbers') % just textdisp(['The numbers are: ' num2str(n)]) % text and No's

    >> disp_demo

    n = 8 1 68 1 6

    Magic NumbersThe numbers are: 8 1 6

  • 7/29/2019 Ch 3 Script M-Files

    22/40

    Output Commands fprintf 1/4

    fprintf

    22

    fprintf('text') orfprintf('format',arg1, arg2,..)

    fprintf_demo.m

    n = [8 1 6];

    fprintf( '%2d %2d %2d\n', n );fprintf('Magic Numbers\nDo Exist!\n') % just textfprintf('The numbers are %d, %d and %d.\n', n)

    >> fprintf_demo

    8 1 6Magic NumbersDo Exist!The numbers are 8, 1 and 6.

    \n new line

    \t horizontal tab%d decimal integer%x hexadecimal%f floating point%*d field width, ..

  • 7/29/2019 Ch 3 Script M-Files

    23/40

    Output Commands fprintf 2/4

    fprintf understands vectors and matrices 2x multiplication table

    23

    times2_table.m

    n = (1:9)';

    times2 = [ 2*ones(9,1) n 2*n ];fprintf('%d x %d = %2d\n', times2')

    >> times2_table2 x 1 = 22 x 2 = 42 x 3 = 62 x 4 = 82 x 5 = 102 x 6 = 122 x 7 = 142 x 8 = 162 x 9 = 18

    >> times2'ans =

    2 2 2 2 2 2 2 2 21 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 18

  • 7/29/2019 Ch 3 Script M-Files

    24/40

    Output Commands fprintf 3/4

    advanced formatting field width and precision

    24

    format_demo.m

    fprintf('%4d %d %5.1f %-5.1f %+5.1f\n', ...

    2, 2, pi, pi, pi );fprintf('%4d %d %5.1f %-5.1f %+5.1f\n', ...

    -2, -2, -pi, -pi, -pi );

    >> format_demo

    2 2 3.1 3.1 +3.1-2 -2 -3.1 -3.1 -3.1

    2 2 3 . 1 3 . 1

    - 2 - 2 - 3 . 1 - 3 . 1

    + 3 . 1

    - 3 . 1

  • 7/29/2019 Ch 3 Script M-Files

    25/40

    Output Commands fprintf 4/4

    Writing into a text file Steps:

    25

    times2_table_file.m

    n = (1:9)';

    times2 = [ 2*ones(9,1) n 2*n ];fid = fopen('times2.txt','w');fprintf(fid, '%d x %d = %2d\n', times2');fclose(fid);

    fopen() fprintf() fclose()

    times2.txt

  • 7/29/2019 Ch 3 Script M-Files

    26/40

    MATLAB Data File

    save and load into/from MATLAB data file save

    load

    26

    save mydata

    save mydata var1 var2 ...

    save mydata var3 -append

    saveascii mydata.txt var1

    loadmydata

    loadmydata.txt

  • 7/29/2019 Ch 3 Script M-Files

    27/40

    Reading from Excel File 1/2

    xlsread Interactive range selection

    27

    a = xlsread('simple.xlsx',-1)

  • 7/29/2019 Ch 3 Script M-Files

    28/40

    Reading from Excel File 2/2

    xlsread Read the entire excel file

    Read a range of data from the excel file

    28

    a = xlsread('simple.xlsx')

    a = xlsread('simple.xlsx','Sheet1','A3:B4')

  • 7/29/2019 Ch 3 Script M-Files

    29/40

    Writing to Excel File

    xlswrite Write data into an Excel file.

    29

    xlswrite_demo.m

    % Excel write demo

    % Write to the first sheet beginning from A1xlswrite('magic.xlsx',magic(4));% Write to a new sheet, 'Magic5', beginning from A1xlswrite('magic.xlsx',magic(5), 'Magic5');% Write to 'Sheet2' beginning from A1

    xlswrite('magic.xlsx',magic(6), 2);

    % Write to 'Sheet3' beginning from B2xlswrite('magic.xlsx',magic(7), 3, 'B2');

  • 7/29/2019 Ch 3 Script M-Files

    30/40

    repeated_hello.m

    t = timer('TimerFcn','say_hello','StartDelay',2,

    'ExecutionMode','fixedDelay','Period', 3);

    Timer

    Repeated action using timer function

    30

    StartDelay

    Period Period Period

    start(t)stop(t) delete(t)

    fixedRate fixedSpacingsingleShot

    say_hello.m

    function say_helloload voicessoundsc(hello,Fs) Try timer_demo.m!!

  • 7/29/2019 Ch 3 Script M-Files

    31/40

    Timer Demo

    A man says 'Hello!' repeatedly.

    31

    timer_demo.m

    % Timer demonstration

    ans = inputdlg('Period in seconds', ...

    'Greeting Man Timer',1,{'3'});

    period = str2double(ans{1});t = timer('TimerFcn','say_hello','StartDelay',1, ...

    'ExecutionMode','fixedDelay','Period', period);

    start(t);

    %% Listen to the voice for a while.

    h = msgbox('Do you want to stop the timer?' , ...

    'Stop Timer');uiwait(h);

    stop(t)

    delete(t)

  • 7/29/2019 Ch 3 Script M-Files

    32/40

    Start-up and Finish Script

    User defined: startup.m, finish.m

    32

    matlabrc.m

    pathdef.m

    startup.m

    finish.m

    MATLAB

    format compact

    cd c:\work

    q='Sure?';

    b=questdlg(q,'Exit

    Request','Yes','No','No');

    switch bcase 'No;

    quit cancel;

    endedit startupsav.m

  • 7/29/2019 Ch 3 Script M-Files

    33/40

    Exercise 1 Prime Factoring v1.0

    Write a script file, 'ifactor.m', which gets anumber from user and prints the number as aproduct of the prime factors. (Hint: factor)

    33

    >> ifactorPrime Factoring v1.0Enter a positive integer:3030 = 1 x 2 x 3 x 5>> ifactorPrime Factoring v1.0

    Enter a positive integer:4040 = 1 x 2 x 2 x 2 x 5

  • 7/29/2019 Ch 3 Script M-Files

    34/40

    Solution 1

    Script

    Screenshot of running 'ifactor'

    34

    ifactor.m

  • 7/29/2019 Ch 3 Script M-Files

    35/40

    Exercise 2 Prime Factoring v1.1

    Write a script file, 'ifactor2.m', which gets anumber from user using a dialog box and

    prints the number as a product of the prime

    factors at a message box.

    [Hint: inputdlg(), msgbox()]

    35

  • 7/29/2019 Ch 3 Script M-Files

    36/40

    Solution 2

    Script and Screenshot

    36

    ifactor2.m

  • 7/29/2019 Ch 3 Script M-Files

    37/40

    Exercise 3 Mean and Variance

    Write a script file, 'icalc.m', which prints themean and the variance of the data in

    'marks.xlsx'.

    [Hint: mean(), var()]

    37

  • 7/29/2019 Ch 3 Script M-Files

    38/40

    Solution 3

    Script

    Screenshot of running icalc

    38

    icalc.m

  • 7/29/2019 Ch 3 Script M-Files

    39/40

    Notes

    39

  • 7/29/2019 Ch 3 Script M-Files

    40/40

    Notes