Examples

  1. Add this line to the script named sort_list.m that you wrote in the Topic Discussion.
        list3 = unique( list1 )

    The results of executing the revised sort_list program:

        >> sort_list
         Type in a vector of integers: [ 9 6 32 12 1 6 91 ]
     
        list1 = 
             9     6    32    12     1     6    91
     
        list2 =
             1     6     6     9    12    32    91
      
        list3 = 
             1     6     9    12    32    91
    
    You should try this script for several vectors to understand how it works. The sort() function is a Matlab function that does exactly what one would think it does. It sorts vectors of numbers into ascending order.

    There are other parameters and options for sort() that you can look up if you are interested. You should be able to figure out by yourself what the Matlab unique() function does.

  2. Write a program named input_demo.m that asks the user for their name, how they feel and the year that they were born in. Your program should then output, the user's name, how they are feeling and their current age. A program which echoes the user's input in this way is useful for learning how to use the input command and the disp command.

    Copy and paste the following script into the m-file editor window. Run it several times to see how it works. Notice that the input() function requires the 's' parameter when the input variable should be a character string.

        %% Test of input
    
        name = input(' Hello, what is your name? ', 's' );
     
        reply = input([' It is good to meet you, ', name, ...
              '. How are you today? '], 's' );
     
        birth_year = input([name, ', what year were you born? ' ]);
        age = 2006 - birth_year;
     
        disp([' ', name, ', you are looking ', reply , ...
                ' today for a ', num2str(age), ' year old person. '] )
    
    The num2str() function is needed to convert a numerical variable to a character string in the disp() function. It is not needed for the character strings. Character strings can be listed one after the other in a vector of character strings, and disp() will print them out in order.

    The age calculation is incorrect if the user has not celebrated their birthday yet this year. This is an example of a semantic error. Semantic errors are not recognized and reported by the programming environment and must be found by thorough testing by the programmer. Syntax errors are those errors that cause the program to not continue executing. Syntax errors produce error messages when the script is run.