Matlab Io Screen

Embed Size (px)

Citation preview

  • 8/3/2019 Matlab Io Screen

    1/20

    ICT Onderzoek LUDIT

    IO_sreen_1

    IO_screen

    MATLAB Screen IO

    MATLAB offers a number of ways for entering data, both on the screen or on file.

    Most of the syntax specifications are copied from the MATLAB help documentation.

    Input from screen

    The input function

    MATLAB can prompt you for input at any time by using the input command. This

    command will display a text string, if specified, and waits for input.Table IO_screen-1. input function

    Function Description

    input Prompts user for input

    user_entry = input('prompt')

    displays prompt as a prompt on the screen,

    waits for input from the keyboard, and

    returns the value entered in user_entry.

    Entering any letter will create an error.

    user_entry = input('prompt','s')

    returns the entered string as a text variable

    rather than as a variable name or numerical

    value. This form will either take numbers

    or strings as entry; the user_entry variable

    will always be a string, even if a number is

  • 8/3/2019 Matlab Io Screen

    2/20

    ICT Onderzoek LUDIT

    IO_sreen_2

    Function Description

    entered.

    The response to the input prompt can be any MATLAB expression, which is evaluated

    using the variables in the current workspace: if you enter a series of numerical values

    between [ ], these values will be considered as a array (this is a way to enter multiple

    data). This command is quick and useful for taking in a single line of keyboard entry.

    Single value input

    An example of the use of input using numerical data is given in demo_input_01.m

    %% use of the input function for an interactive approach%ht = input('Enter the height of the cylinders (m)? ');mx_diam = input('Enter the maximum diameter (m)? ');

    Running the script produces this result

    >> demo_input_01

    Enter the height of the cylinders (m)? 5

    Enter the maximum diameter (m)? 6

    When the 's' option is specified in the input command (input(prompt,s)), theentered string is returned as-is, as shown in demo_input_02.m. Matlab provides a set of

    string conversion functions that can be applied to extract the right data out of the string.

    Running the script produces this result

    >> demo_input_02

    Enter your data: this is a string

    Name Size Bytes Class Attributes

    inp_data 1x16 32 char

    inp_data =

    this is a string

    Multiple value input

    An example of the use of input where multiple values can be entered is given in

    demo_input_03.m

    %vec = input('Enter a set of numerical values (Enter the values between [ ])');

  • 8/3/2019 Matlab Io Screen

    3/20

    ICT Onderzoek LUDIT

    IO_sreen_3

    Running the script produces this result

    >> >> demo_input_03

    Enter a set of numerical values (Enter the values between [ ])[1 2 3]

    mean of the values entered:

    mean_calc =

    2

    TIP: Be sure to tell the user how to enter the data, especially if it is to

    be entered according to a specific format

    Input dialog boxes

    Besides the standard input command, MATLAB also provides a few dialog boxes that

    can be used to enter data interactively. These graphical elements are easy to include in

    (existing) MATLAB code; this approach is different from the MATLAB GUI way!

    MATLAB is very well suited for providing a proof of concept. If you want to

    demonstrate quickly that a concept is fundamentally correct, you code it and debug it

    quickly in MATLAB. Most of the times these programs have some tunable parameters

    which need to be adjusted by the user. It is of no good practice to let the user dig into

    your code to change a parameter, but it is preferable that these values are entered using a

    dialog box. MATLAB's own ready-to-go dialog boxes are almost always sufficient forthis.

    Table IO_screen-2. Input dialog boxes

    Function Description

    inputdlg Create input dialog box

    answer = inputdlg(prompt,dlg_title,num_lines,defA

    and returns user input for multiple prompts in the cell array.

    prompt is a cell array containing prompt strings.

    dlg_title specifies a title for the dialog box.num_lines specifies the number of lines for each user-entered

    value. num_lines can be a scalar, column vector, or matrix.

    defAns specifies the default value to display for each prompt.

    defAns must contain the same number of elements as prompt

    and all elements must be strings.

    listdlg Create a list dialog box that enables the user to select one or

    more items from a list.

  • 8/3/2019 Matlab Io Screen

    4/20

    ICT Onderzoek LUDIT

    IO_sreen_4

    Function Description

    [Selection,ok] = listdlg('ListString',S)

    Selection is a vector of indices of the selected strings (in single

    selection mode, its length is 1). Selection is [ ] when ok is 0. ok

    is 1 if you click the OK button, or 0 if you click the Cancel

    button or close the dialog box.

    Double-clicking on an item or pressing Return when multiple

    items are selected has the same effect as clicking the OK

    button.

    menu Generate menu of choices for user input

    k = menu('mtitle','opt1','opt2',...,'optn')

    the menu is displayed with a title is in the string variable

    'mtitle' and the choices are string variables 'opt1', 'opt2', and so

    on.

    menu returns thenumber of the selected menu item

    The inputdlg function

    This command is useful for taking in multiple lines from the keyboard all at once.

    The code for the inputdlg consists of two parts. The first creates the box with appropriateentry labels and title, and the second where the entries are converted to a form that is

    usable by Matlab. The four arguments (prompt, dlg_title, num_lines, and defAns) are

    variables; they must be defined in advance. The entries initially are returnded as a cell

    array and must be converted before they can be used in calculations. This is done using

    curly brackets {} to access the cell contents.

    Numerical data, characters, and file names can all be entered in a dialog box. Inside a

    dialog box you can move from field to field either with the mouse or by using the tab

    key.

    An example of the use of inputdlg is given in demo_inputdlg_01.m

    % define the labels for the individual entries (between curly braces {})

    prompt = { 'Temperature (K)', 'Pressure (Pa)', 'Filename'};

    % define a title for the dialog boxdlg_title = 'Data Entry for Problem 1';

    % create the dialog box with the inputdlg commandanswer = inputdlg(prompt, dlg_title);

    Running the program produces this result

  • 8/3/2019 Matlab Io Screen

    5/20

    ICT Onderzoek LUDIT

    IO_sreen_5

    Figure IO_screen-1. dialog box demo_inputdlg_01

    A more complex example, with predefined default values is given in

    demo_inputdlg_02.m

    % define the labels for the individual entries (between curly braces {})prompt = { 'Entry 1', 'Entry 2', 'Entry 3'};

    % define a title for the dialog boxdlg_title = 'Data Entry for Problem 2';

    % define default answersdefAns = {'[1 2 3]', 'water', 'A'};

    % create the dialog box with the inputdlg commandanswer = inputdlg(prompt, dlg_title, [3;2;1], defAns);

    Running the program produces this result

  • 8/3/2019 Matlab Io Screen

    6/20

    ICT Onderzoek LUDIT

    IO_sreen_6

    Figure IO_screen-2.dialog box demo_inputdlg_02

    The listdlg function

    If you have a list of options where can be chosen from, listdlg is the solution to go, it is a

    powerful function allows the user to select one or more choice(s) from a list of items.

    An example of the use of listdlg is given in demo_listdlg_01.m

    % prepare the list of options to select fromformat_list = [{'fig - MATLAB figure'}, {'jpg - JPEG'}, ...

    {'bmp - Windows bitmap'}, {'emf - Enhanced metafile'}, ...{'eps - EPS Level 1'}, {'m - MATLAB M-file'}, ...{'pbm - Portable bitmap'}, {'pcx - Paintbrush 24-bit'}, ...{'pgm - Portable Graymap'}, {'png - Portable Network Graphics'}, ...{'ppm - Portable Pixmap'}, {'tif - TIFF (kompr.)'}];

    [selection, was_OK] = listdlg('PromptString', 'Select file formats to save

    pictures:', ...'ListSize', [250 200], 'SelectionMode', 'single', ...'ListString', format_list);

    Running the program produces this result

  • 8/3/2019 Matlab Io Screen

    7/20

    ICT Onderzoek LUDIT

    IO_sreen_7

    Figure IO_screen-3. dialog box demo_listdlg_01

    The menu function

    If a very limited choice of parameters is available to choose from, then the menufunction can be used. The user has only to click on the right button, and the index of its

    choice is returned as a result

    An example of the use of menu is given in demo_menu_01.m

    % ask the user the color of the plotk = menu('Choose a color','Red','Green','Blue');

    % select the color depending on the index chosencolor = ['r','g','b'];

    Running the program produces this result

  • 8/3/2019 Matlab Io Screen

    8/20

    ICT Onderzoek LUDIT

    IO_sreen_8

    Figure IO_screen-4. menu dialog box demo_menu_01.m

    Output to screen

    The disp function

    Table IO_screen-3. disp function

    Function Description

    dispDisplay text or array

    disp(X)

    displays an array, without printing the

    array name. IfX contains a text string, the

    string is displayed.

    Note that disp does not display empty

    arrays.

    TIP: A combination of text and variables is possible by concatenation.

    A numerical variable has to be transformed into a string first.

    An example of the use of menu is given in demo_menu_01.m

    % put some text onto the screendisp('This is text');

    % put the numerical values onto the screendisp(x);

  • 8/3/2019 Matlab Io Screen

    9/20

    ICT Onderzoek LUDIT

    IO_sreen_9

    % combine some text and numerical values (numerical values have to be% transformed into string formatdisp(['First element= ' num2str(x(1)) ' Last element= ' num2str(x(10))]);

    Interactive IO

    Several build in dialog boxes are already available in MATLAB. The most interesting are

    given in the table below. Check the MATLAB HELP for more on dialog boxes an the

    format to use.

    Table IO_screen-4. Some interesting built-in dialog boxes

    Function Description

    errordlg Create error dialog box

    errordlg('errorstring','dlgname','on')

    a dialog box named 'dlgname' that contains the string 'errorstring'.

    'on' specifies whether to replace an existing dialog box having the

    same name. 'on' brings an existing error dialog having the same

    name to the foreground.

    helpdlg Display help dialog box

    helpdlg('helpstring','dlgname')

    displays a dialog box named 'dlgname' containing the string

    'helpstring'. MATLAB wraps the text in 'helpstring' to fit the width

    of the dialog box. The dialog box remains on your screen until you

    press the OK button or the Enter key.

    questdlg Create question dialog box

    button= questdlg('qstring','title','default')

    'qstring' is a cell array or a string that automatically wraps to fit

    within the dialog box.

    'title' is displayed in the dialog's title bar.

    The dialog has three default buttons, Yes, No, and Cancel. If the

    user presses one of these three buttons, button is set to the name of

    the button pressed. If the user presses the close button on the dialog,

    button is set to the empty string. If the user presses the Return key,

    button is set to 'Yes'.

    warndlg Create warning dialog box

  • 8/3/2019 Matlab Io Screen

    10/20

    ICT Onderzoek LUDIT

    IO_sreen_10

    Function Description

    h = warndlg('warnstring','dlgname',createmode)

    specifies whether a warning dialog box is modal or non-modal.

    Valid values for createmode are 'modal', 'non-modal', and 'replace'.

    If createmode is 'modal' or 'replace', the first available warning

    dialog box with the specified title is updated to reflect the new

    properties of the warning dialog box. All other such warning dialog

    boxes are deleted. If createmode is 'non-modal', the warning dialog

    box is not replaced and a new handle is created. The default value

    for createmode is 'non-modal'.

    waitbar Open waitbar

    h = waitbar(x,'title')

    TIP: When using errordlg, you have to make a choice if you want to

    popup error boxes for each error message or if you want to recycle the

    error box and have the same box displaying different error messages.

    This is done by specifying the third parameter 'on'.

    TIP: The default mode of warndlg, will always create a new dialog boxto show a new warning.

    TIP: The waitbar command is especially useful, when you have for-

    loops in your program, then you can visualise the time passing by.

    An example of the use these different interactive dialog boxes is given in

    demo_interactivedlg_01.m

    while 1

    % ask the user to choose from the optionsk_choice = menu('Choose a dialog box','errordlg', 'helpdlg', 'warndlg',

    'questdlg', 'waitbar', 'stop');

    % use the switchswitch k_choice

  • 8/3/2019 Matlab Io Screen

    11/20

    ICT Onderzoek LUDIT

    IO_sreen_11

    case 1

    % the same error dialog box is kept, watch the time changingstr_1 = ['OUCH! This is the right time: ' datestr(now)];errordlg(str_1, 'error_1', 'on');

    case 2% the same help dialog box is kept, watch the time changing,

    % click ok, to make the box dissappearstr_2 = ['FYI: ' datestr(now)];helpdlg(str_2, 'help_2');

    case 3% use an extra inputdlg window to enter data

    prompt = { 'enter a number'};dlg_title = 'Data Entry for Problem warning';

    defAns = {'4'};% create the dialog box with the inputdlg commandanswer = inputdlg(prompt, dlg_title, 1, defAns);

    x = str2num(answer{1});if ((x1))

    warndlg('Inadequate range. Value set to 0.5','Input Error')end

    case 4% a default 2 button question box is used

    answer=questdlg('Do you want to install this software?');if strcmp(answer,'Yes')

    license=['LICENSE this software is licensed free of charge for

    educational use '];license=questdlg(license,'Do you agree?','No');

    end

    case 5% the computational loop takes 5 seconds

    h = waitbar(0,'Please wait...');for i=1:5,

    pause(1);waitbar(i/5)

    endclose(h)

    case 6break

    end

    end

    Running the program produces this result

  • 8/3/2019 Matlab Io Screen

    12/20

    ICT Onderzoek LUDIT

    IO_sreen_12

    Figure IO_screen-5. Different interactive dialog boxes

    Formatted IO

    The disp function can be used to put a string onto the screen, if you want the string to

    have a specified format, the best way is to build up the string with the sprintf command

    and use format specifiers.

    The sprintf function

    Table IO_screen-5. sprinfcommand

    Function Description

    sprintf Write formatted data to string

    [s, errmsg] = sprintf(format, variables)

    format is the specified format. It consists of a chain of format

    specifiers (place holders) variables is the list of variables to print

    according to the specified format.

    returns

    The result is returned in a string variable s. An error message string

    errmsg is returned if an error occurred. errmsg is an empty matrix

    if no error occurred.

    The format specification used in MATLAB is based on the model used inthe C programming language. Format specifiers (starting with %) are used

    to build the layout of the string to print.

  • 8/3/2019 Matlab Io Screen

    13/20

    ICT Onderzoek LUDIT

    IO_sreen_13

    format placeholders

    Formatting takes place via placeholders within the format string. For example, if a

    program prints out a zip code, a prefix could be "ZIP code: ". To denote that an integer

    is to be shown immediately after that message, the format string "ZIP code: %d." is used.

    Table IO_screen-6. Format specification

    specification

    '% [flag][width][.precision]type' syntax for a format

    placeholder

    %-12.5e

    Table IO_screen-7.Optional format specifier

    Flag Can be optional

    + Will always denote the sign '+' or '-' of a

    number (the default is to omit the sign for

    positive numbers). Only applicable to

    numeric types.

    - Will left-align the output of this

    placeholder (the default is to right-align the

    output).

    0 Pad arguments with leading zeros '0'

    (instead of spaces) to left fill a fixed length

    field.

    Width

    number Causes to pad the output of this

    placeholder with spaces until it is at least

    number characters wide. If number has a

    leading '0', then padding is done with '0'

    characters.

    .Precision

    number For non-integral numeric types, causes the

    decimal portion of the output to be

    expressed in at least numberdigits. For the

    string type, causes the output to be

    truncated at numbercharacters.

  • 8/3/2019 Matlab Io Screen

    14/20

    ICT Onderzoek LUDIT

    IO_sreen_14

    Table IO_screen-8. Type format specifier

    Type

    c Print a char (character).

    d Print an int as a signed decimal number.

    E, e rint a double value in standard form ([-

    ]d.ddd e[+/-]ddd). 'e' uses lower-case

    letters, 'E' uses upper-case letters.

    f Print a double in normal (fixed-point)

    notation.

    G, g Print a double in either normal or

    exponential notation, whichever is more

    appropriate for its magnitude. 'g' uses

    lower-case letters, 'G' uses upper-case

    letters. This type differs slightly from

    fixed-point notation in that insignificant

    zeroes to the right of the decimal point are

    not included. Also, the decimal point is not

    included on whole numbers.

    o Print an unsigned int in octal.

    s Print a character string.

    X, x Print an unsigned int as a

    hexadecimal number. 'x' uses lower-case

    letters and 'X' uses upper-case.

    Table IO_screen-9. Escape sequences

    \n New line

    \t Horizontal tab

    \b Backspace

    \r Carriage return

    \f Form feed

  • 8/3/2019 Matlab Io Screen

    15/20

    ICT Onderzoek LUDIT

    IO_sreen_15

    \\ print a backslash \ symbol

    %% %% print a percent symbol %

    Printing a string

    Strings will be pritned using the %Ls format specifier. L specifies the length of the string.

    The string will be right-aligned (if the string is smaller than L characters). The flag -

    will left align the string. If the length is not specified, the length will be equal to the

    length of the string variable to be printed.

    An example of the string formating is given in demo_format_01.m

    % most simple formats = sprintf('Hello world \n');disp(s)

    % changing the format - use s typestr_hello = 'Hello world';sprintf('%s',str_hello)

    % default right alignmentsprintf('%30s',str_hello)

    % left alignmentsprintf('%-30s',str_hello)

    % what happens if the specified length is smaller than the string?

    % the string will still be printed completelysprintf('%5s',str_hello)

    % The "%s" code inserts text in the template.fileName = 'home/assignments/a1.txt';s = sprintf('My first assignment is in the file, "%s" \n', fileName);disp(s)

    % digit string specifying the minimum number of digits to be printeds = sprintf('%5c','matlab');disp(s)

    s = sprintf('\n');disp(s)

    % watch out where to place the new line escape sequence

    s = sprintf('%5c \n','matlab');disp(s)

  • 8/3/2019 Matlab Io Screen

    16/20

    ICT Onderzoek LUDIT

    IO_sreen_16

    s = sprintf('%c','matlab');disp(s)s = sprintf('\n');disp(s)

    Running the program produces this result

    >> demo_format_01

    Hello world

    ans =

    Hello world

    ans =

    Hello world

    ans =

    Hello world

    ans =

    Hello world

    My first assignment is in the file, "home/assignments/a1.txt"

    m a t l a b

    m

    a

    t

    l

    a

    b

    matlab

    Printing numbers

    A real number will be printed following the %+- L.D type,

    format. L is the total length of the printed number

    (decimal point included). D is the number of digits to be

    printed to the right of the decimal point. The default

    alignment is right, putting a - in front will left align.

  • 8/3/2019 Matlab Io Screen

    17/20

    ICT Onderzoek LUDIT

    IO_sreen_17

    An example of the string formating is given in demo_format_02.m

    % Numbers can be inserted in the text. "%f is a code for insert-% ing a number.

    s = sprintf('First number = %f, next number = %f \n', 11, 2/3);disp(s)

    % The number of places after the decimal point can be% controlled: "%.2f" produces two digits after the point.s = sprintf('First number = %.2f, next number = %.9f \n', 1/3, 1/3);disp(s)

    % the same numer, but printed with the exponential type es = sprintf('First number = %.2e, next number = %.9E \n', 1/3, 1/3);disp(s)

    % The special sequence, "\n", starts a new line.s = sprintf(' Pi to 2 places %.2f \n Pi to 12 places %.12f \n', pi,pi);

    disp(s)

    % The "%e" code displays numbers in scientific notation:s = sprintf(' Pi = %e Million = %e 1/700 = %E \n', pi, 1E6, 1/700);disp(s)

    % For more (or fewer) places after the decimal pointX=9.12345678901234E-8;

    s = sprintf(' 2 places %.2e; 14 places %.14e \n', X,X);disp(s)

    % A digit string including a period (.)

    s = sprintf('%10.4f',123.456);disp(s)

    % printing 100.35 with different type specifierssprintf('%5g',100.35)sprintf('%d',100.35)

    % printing 100 with different type specifierssprintf('%c',100)

    sprintf('%s',100)sprintf('%d',100)sprintf('%g',100)sprintf('%6.2f',100)sprintf('%6.2e',100)sprintf('%o',100)

    Running the program produces this result

  • 8/3/2019 Matlab Io Screen

    18/20

    ICT Onderzoek LUDIT

    IO_sreen_18

    >> demo_format_02

    First number = 11.000000, next number = 0.666667

    First number = 0.33, next number = 0.333333333

    First number = 3.33e-001, next number = 3.333333333E-001

    Pi to 2 places 3.14

    Pi to 12 places 3.141592653590

    Pi = 3.141593e+000 Million = 1.000000e+006 1/700 = 1.428571E-003

    2 places 9.12e-008; 14 places 9.12345678901234e-008

    123.4560

    ans =

    100.35

    ans =

    1.003500e+002

    ans =

    d

    Warning: The argument for the %s format specifier must be of type char (a string).

    > In demo_format_02 at 53

    ans =

    d

    ans =

    100

    ans =

    100

    ans =

    100.00

    ans =

    1.00e+002

  • 8/3/2019 Matlab Io Screen

    19/20

    ICT Onderzoek LUDIT

    IO_sreen_19

    ans =

    144

    TIP : sprintf can be used as a vector command, if the variable is not

    a scalar, the format is utilized for the elements of the array (column by

    column)

    An example of the string formating is given in demo_format_03.m

    % a vectorx = 1:10;s = sprintf(' %d ,',x);

    disp(s)

    % a matrix (column wise)x = [1 2; 3 4];s = sprintf(' %d ,',x);

    disp(s)

    % building a 2-column structure% the data is stored in a vectorz = [];

    x = 1:10;for i=1:length(x)

    z = [z ,x(i), sin(x(i))];

    end;s = sprintf('%04.1f | %+8.6e \n ', z );disp(s)

    Running the program produces this result

    >> demo_format_03

    1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ,

    1 , 3 , 2 , 4 ,

    01.0 | +8.414710e-001

    02.0 | +9.092974e-001

    03.0 | +1.411200e-001

    04.0 | -7.568025e-001

    05.0 | -9.589243e-001

    06.0 | -2.794155e-001

    07.0 | +6.569866e-001

    08.0 | +9.893582e-001

    09.0 | +4.121185e-001

    10.0 | -5.440211e-001

  • 8/3/2019 Matlab Io Screen

    20/20

    ICT Onderzoek LUDIT

    IO_sreen_20

    The fprintf command is analogous to the sprintf command and is used for a

    formatted print into a file.