fprintf conversion character use \c or \s?
5 views (last 30 days)
Show older comments
I am trying to create a table, without using the table function, that lists the values from two lists. Because this is a function I didn't hard code the for loop, so it should work for any amount of values. The results list is numbers that successfully prints to the screen. The countries list is as follows:
'AUS'
'AUT'
'BLR'
'CAN'
'CHN'
'CRO'
'CZE'
etc
However the function only prints the first character of each country with this output:
Countries Gold Silver Bronze Total
A 2 1 0 3
A 4 6 6 16
B 1 1 1 3
C 14 7 5 26
C 5 2 4 11
C 0 2 1 3
C 2 0 4 6
etc
function print_country_results(countries,results)
fprintf ('Countries Gold Silver Bronze Total\n')
for n = 0:length(results)
fprintf (' %c %2.0f %2.0f %2.0f %2.0f\n',[countries(n+1,1); results(n+1,1); results(n+1,2); results(n+1,3); results(n+1,4)])
if n == length(results)
break
end
end
end
I know that %s will return a string array, instead of using %c for a single character, but when I use %s I receive the error message that
0 Comments
Answers (1)
Star Strider
on 17 Nov 2019
Putting character arrays and numeric variable types together in a matrix is not appropriate.
Try this instead:
countries = ['AUS'
'AUT'
'BLR'
'CAN'
'CHN'
'CRO'
'CZE'];
results = [ 2 1 0 3
4 6 6 16
1 1 1 3
14 7 5 26
5 2 4 11
0 2 1 3
2 0 4 6];
fprintf ('Countries Gold Silver Bronze Total\n')
for n = 0:length(results)-1
fprintf (' %s %2.0f %2.0f %2.0f %2.0f\n',countries(n+1,:), results(n+1,1), results(n+1,2), results(n+1,3), results(n+1,4))
if n == length(results)
break
end
end
You might be able to do that with string arrays (I didn’t test that), although certainly not with character arrays.
0 Comments
See Also
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!