MATLAB I/O COMMANDS AND
BUILT-IN MATHEMATICAL
FUNCTIONS
Dr. Vibhu Jately
disp (Display text or variable)
• Displays text or variable value without formatting.
• Simple, but limited compared to fprintf.
Example
x = 25;
disp('The value of x is:')
disp(x)
Output
The value of x is:
25
fprintf (Formatted print)
• More powerful than disp.
• Allows you to format numbers, strings, new lines, etc.
Example
x = 25;
fprintf('The value of x is %d\n', x);
y = 3.14159;
fprintf('The value of pi is %.2f\n', y);
Output
The value of x is 25
The value of pi is 3.14
fprintf Format Specifiers Cheat Sheet
Specifier Meaning Example Code Output
fprintf('Value = %d\n',
%d Integer (decimal) Value = 25
25)
Floating-point (default 6 fprintf('Pi = %f\n',
%f Pi = 3.141590
decimals) 3.14159)
Floating-point with 2 fprintf('Pi = %.2f\n',
%.2f Pi = 3.14
decimal places 3.14159)
Scientific notation fprintf('Val = %e\n',
%e Val = 1.234500e+04
(exponential form) 12345)
Compact form (%f or fprintf('%g\n',
%g 1.23e-05
%e, whichever shorter) 0.0000123)
fprintf('Hello %s\n',
%s String Hello MATLAB
'MATLAB')
fprintf('Progress =
%% Prints % symbol Progress = 80%
80%%\n')
\n New line (enter) fprintf('Line1\nLine2\n') Line1Line2
\t Tab space fprintf('X\tY\n') XY
Built-in Mathematical Functions
(a) sum – Adds elements (b) mean – Average
Example Example
A = [1 2 3 4]; A = [10 20 30 40];
total = sum(A) avg = mean(A)
Output Output
total = 10 avg = 25
(c) max – Maximum value (d) min – Minimum value
Example Example
A = [3 7 2 9 5]; A = [3 7 2 9 5];
m = max(A) m = min(A)
Output Output
m=9 m=2
(e) linspace – Generates linearly spaced vectors
Example
x = linspace(0,10,5) % 5 points between 0 and 10
Output
x = 0 2.5 5.0 7.5 10
(f) zeros – Matrix of zeros
Example
Z = zeros(2,3)
Output
Z=
0 0 0
0 0 0
(g) ones – Matrix of ones (h) eye – Identity matrix
Example Example
O = ones(3,2) I = eye(3)
Output Output
O= I=
1 1 1 0 0
1 1 0 1 0
1 1 0 0 1
(i) rand – Random numbers between 0 and 1
Example
R = rand(2,3)
Output (values will change every time):
R=
0.8147 0.1270 0.6324
0.9058 0.9134 0.0975