Examples
- 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. Thesort()
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. - 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 theinput
command and thedisp
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. '] )
Thenum2str()
function is needed to convert a numerical variable to a character string in thedisp()
function. It is not needed for the character strings. Character strings can be listed one after the other in a vector of character strings, anddisp()
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.