Examples

  1. There are a couple of differences between just omitting the semi-colon and using the disp() function to output information to the user.
        >> x = [1 2 3 4];
        >> x
    
        x =
    
             1     2     3     4
    
        >> disp(x);
             1     2     3     4
    
        >> 
    The first statement enters values into the variable x and suppresses the output with the semicolon.

    The second statement x outputs x and its contents.

    The statement disp(x) displays just the contents of x even though the statement ends with a colon.

  2. To display character strings, enclose the text in single quotes. Multiple text strings and variables can be output with one disp() command, but they must be wrapped into a single matrix. For example:
    >> mascot = 'Bucky Badger';
    >> disp( [ 'The Wisconsin mascot is ' , mascot , '.' ] );
    The Wisconsin mascot is Bucky Badger.
    

    Notice that the outputted character strings are concatenated, or jammed together. So, if you want a space between the strings, you must include a space in one of the strings or as a separate string in the matrix. For example:

    >> disp( [ 'hello' , 'world' ] );
    helloworld
    >> disp( [ 'hello ', 'world' ] );
    hello world

    Note: The disp() function will display output to the user even if a semi-colon follows the statement.

  3. Sometimes we want to make a program more user-friendly by giving output like "The average is 7.56" instead of just displaying "7.56". To do something like this, we need to use the num2str() function.

    In Matlab, numbers are stored differently than text; this allows Matlab to handle math operations more efficiently. Text is stored as a string of characters. Numbers are stored as numbers. For disp() to work, the information in the matrix to display must be either all numbers or all strings of characters.

    The num2str() function converts numbers into their string equivalents. To display the message mentioned earlier, the following code fragment can be used:

        >> avg = 7.56;
        >> disp( [ 'The average is ' , num2str(avg), ' inches of rain per year' ] )
        The average is 7.56 inches of rain per year
    Notice the blank space after the word is so that the output is separated and easier to read. Use the num2str() function whenever you wish to output the value of numbers and some textual information either before or after the value.