Page 15 - Applied Numerical Methods Using MATLAB
P. 15
4 MATLAB USAGE AND COMPUTATIONAL ERRORS
1.1.3 Input/Output of Data Using Keyboard
The command ‘input’ enables the user to input some data via the keyboard.
For example,
>>x = input(’Enter x: ’)
Enter x: 1/3
x = 0.3333
Note that the fraction 1/3 is a nonterminating decimal number, but only four
digits after the decimal point are displayed as the result of executing the above
command. This is a choice of formatting in MATLAB. One may choose to
display more decimal places by using the command ‘format’, which can make
a fraction show up as a fraction, as a decimal number with more digits, or even
in an exponential form of a normalized number times 10 to the power of some
integer. For instance:
>>format rat %as a rational number
>>x
x = 1/3
>>format long %as a decimal number with 14 digits
>>x
x = 0.33333333333333
>>format long e %as a long exponential form
>>x
x = 3.333333333333333e-001
>>format hex %as a hexadecimal form as represented/stored in memory
>>x
x = 3fd5555555555555
>>format short e %as a short exponential form
>>x
x = 3.3333e-001
>>format short %back to a short form (default)
>>x
x = 0.3333
Note that the number of displayed digits is not the actual number of significant
digits of the value stored in computer memory. This point will be made clear in
Section 1.2.1.
There are other ways of displaying the value of a variable and a string on the
screen than typing the name of the variable. Two useful commands are ‘disp()’
and ‘fprintf()’. The former displays the value of a variable or a string without
‘x= ’or ‘ans = ’; the latter displays the values of several variables in a specified
format and with explanatory/cosmetic strings. For example:
>>disp(’The value of x = ’),disp(x)
%disp(’string_to_display’ or variable_name)
The value of x = 0.3333
Table 1.1 summarizes the type specifiers and special characters that are used in
‘fprintf()’ statements.
Below is a program that uses the command ‘input’ so that the user could
input some data via the keyboard. If we run the program, it gets a value of the