e-Mathematics > Matrix Algebra

Input and Output

The input function is used for managing an interactive dialog with a user. For example,
n = input('Pick a number: ')
prints the prompt “Pick a number:” and waits for the user to enter a value. The string preceding the [return] entered by the user is evaluated as an expression. If you want a matrix to be evaluated, you must enter it in one line such as [2 1 3; 4 2 1; 6 2 3].

Matlab/Octave normally prints the value of an expression as soon as it has been evaluated unless you add the semicolon (;) to suppress it. To print the value of a variable without printing its name, use the function disp(x). It displays the value of x, and x can be a vector. For example,

disp(['The value of number is ', num2str(n)])
has the vector ['The value of number is ', num2str(n)] of strings, and it displays “The value of number is 10” if $ n = 10$. The function num2str(n) converts a number n to a string.

But the disp function is not very flexible. The function fprintf is available for formatted output. It is modelled after the C language functions of the same name.

n = 10;
x = 2.35;
fprintf('The value of n is %d.\n The value of x is %f.\n', n, x);
The fprintf function can be used to print any number of arguments. This example shows the use of the `%d' conversion to print an integer, the `%f' conversion to print a real number, and produces the following output:
The value of n is 10.
The value of x is 2.35.

The format of the output produced by disp is controled by format command:

format short e
This enables us to display output with an e format. For example, pi is displayed as “3.14e+00”. The option “long” will try to print numbers with at least 15 significant figures:
format long
Then pi is displayed as “3.14159265358979”. The default format is “short” and it can be brought back by “format short”.


© TTU Mathematics