Inserting a space when printing characters using fprintf

185 views (last 30 days)
I have an array of characters assigned to variable m20 in the format of
CGNU
AEOS
NRRA
I am supposed to have a printed output of 'CAN GER NOR USA' but I am getting 'CANGERNORUSA' with the following code
fprintf('Countries with at least 20 medals: %s \n',m20)
if I were to add 5.0 infront of the %s placeholder, my outputs just vanishes instead of printing.
How can I insert space after printing 3 characters?

Accepted Answer

Jan
Jan on 20 Nov 2016
Str = ['CGNU'; ...
'AEOS'
'NRRA'];
CStr = cellstr(Str.'); % Transposing is important
fprintf('Countries with at least 20 medals:');
fprintf(' %s', CStr{:}); % Or: fprintf(' %c%c%c', Str)
fprintf('\n')

More Answers (1)

Mark McBroom
Mark McBroom on 20 Nov 2016
You must have stripped out the spaces in m20 before printing. Either add spaces back into m20 before printing or change print statement to this:
fprintf('Countries with at least 20 medals: %3s %3s %3s %3s\n',m20(1:3), m20(4:6), ...
m20(7:9), m20(10:12));
  1 Comment
Star Strider
Star Strider on 20 Nov 2016
Edited: Star Strider on 20 Nov 2016
@Linggeas Kisten — Please learn to use the [{}Code] button to format your code. That will help significantly.
I formatted it for you, but not in time for ‘Mark M’ to benefit from it.
m20 = ['CGNU'
'AEOS'
'NRRA'];
fprintf('Countries with at least 20 medals: ')
fprintf(1,'%c%c%c ', m20)
fprintf('\n')
Countries with at least 20 medals: CAN GER NOR USA

Sign in to comment.

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!