next up previous
Next: Plotting Up: MATLAB summary Previous: Arithmetic operators

Displaying output


The default in MATLAB is to display all output. To override this we use a semi-colon at the end of the line, as in the following example:
>> x=1

x =

     1

>> x=1;
>>
Alternatively, to print variables we can use
>> disp(x)
     1

>>
and this works for arrays as well:
>> x=[1; 2; 3; 4; 5];
>> disp(x)
     1
     2
     3
     4
     5

>>
A more flexible and sophisticated form of output is provided by the fprintf command, which is similar to that used in the C programming language. Here is an example:
>> x=pi; y=1/x; 
>> fprintf(' x = %8.6f y = %8.6g \n x*y = %5.3f \n', x,y,x*y)
 x = 3.141593 y =  0.31831 
 x*y = 1.000 
>>
In this command we issue instructions as to how the variables x, y and x*y, which appear as arguments to fprintf after the quoted string, should be printed. These instructions (the FORMAT) are contained between the quotes. Anything between quotes will be printed out as is, unless preceded by a special character such as % or tex2html_wrap_inline168 . Thus we see that 'x = ' is printed out, and then %8.6f instructs MATLAB as to how the value of the variable x should be printed, in this case in floating format, with at least 8 spaces allocated to x, with 6 digits after the decimal point. The %8.6g instruction works similarly, but reduces to exponential format if the number to be printed is very big or very small. Finally, note the use of tex2html_wrap_inline168 n, that gives a new line. fprintf also works for arrays: use help fprintf for details.




Charlie Macaskill
Fri Mar 5 16:05:28 EST 1999

Copyright © University of Sydney 2003