MATLAB programming tips 2 - Input and Output Commands
Matlab Programming Tips
Part 2– Input / Output Commands (Review)
input - Prompt for user input.
Input is the simple basic command to request the
Displays a prompt text for the user to understand
what data to be entered and waits for the user to
input a value and press the Return key.
i = input('Enter the current value:')
str = input(‘text’,'s') returns the entered text as a MATLAB
string, without evaluating expressions.
Read data as string and convert to the other formats
based on the definition.
X = sscanf(str, format, size)
Reads data from the vector str, converts it according to the
format, and store the results in array X.
Argument ‘size’ is optional.
disp - (display) command displays variable values
or text on screen
Displays each time on new line.
Doesn't print variable name
disp(variable_name) or disp('text string')
fprintf - Means file print formatted
'fprintf' is used to formats data and displays the
results on the screen and to write the data in to a text
Can write to screen or to a file
Can mix numbers and text in output
Have full control of output display
Basic Syntax is
fprintf('Text to display')
>> fprintf( 'How are you' )
How are you>>
Problem – Command Window displays prompt (>>) at end of text,
not at start of next line!
To make the prompt to appear on the start of a new line,
n at the end of the fprintf text
>> fprintf( Electrical Engineeringn' )
Use n in middle of text to make MATLAB display
remainder of text on next line
>> fprintf(' Electrical nEngineering')
To format the display data, the formatting operators
A formatting operator starts with a percentage
sign, %, and ends with a conversion character.
Common conversion specifiers:
%f fixed point (decimal always between 1's and 0.1's place,
e.g., 3.14, 56.8
%e scientific notation, e.g, 2.99e+008
%d integers (no decimal point shown)
%s string of characters
>> fprintf( 'Joe is %d weighs %f kilos', age,
>> fprintf( 'Joe weighs %f kilos', n1 )
fprintf to format the output
fprintf to format the output …
>> age = 35;
>> weight = 75.25;
>> fprintf( 'Joe is %d weighs %f kilosn', age, weight )
Joe is 35 weighs 75.250000 kilos
>> fprintf( 'Joe weighs %4.4f kilosn', weight )
Joe weighs 75.2500 kilos
>> fprintf( 'Joe weighs %4.2f kilosn', weight )
Joe weighs 75.25 kilos
fprintf to format the output…
To display a percent sign, use %% in the text
To display a single quote, use ' ' in the text (two
sequential single quotes)
To display a backslash, use in the text (two