MATLAB: How to print the result of a function using fprintf? (matrix and string!)

fprintfmatrix

The variable countries is a 27×1 column vector with 3 letter abbreviations (ex. 'CAN'). Results is a 27×4 matrix with values ranging from 0-40 ish. Why can't I print them together or row by row?
I want the result to look like this:
Country Gold Silver Bronze
CAN 2 1 3
ITA 3 1 4
… etc.
My code:
Please skip to the bottom of this code for the part I'm having issues with.
function [] = Untitled6()
load('olympics.mat')
results = zeros(size(countries,1),4);
results = compute_medals(gold,silver,bronze,countries);
print_country_results(countries,results);
end
function results = compute_medals(gold,silver,bronze,countries);
% computes number of gold, silver, bronze medals and
% total medal tally for a given country and a given sport type
% results = zeros(size(countries,1),4);
for i = 1:length(countries)
country = countries(i, :);
goldCount = 0;
silverCount = 0;
bronzeCount = 0;
for j = 1: length(gold)
if country == gold(j, :)
goldCount = goldCount+ 1;
end
if country == silver(j, :)
silverCount = silverCount + 1;
end
if country == bronze(j, :)
bronzeCount = bronzeCount + 1;
end
end
results(i,1) = goldCount;
results(i,2) = silverCount;
results(i,3) = bronzeCount;
results(i,4) = goldCount + silverCount + bronzeCount;
end
results
end
% HERE! Below is the part I'm having issues with! Please Help!
function [ ] = print_country_results(countries,results)
% prints formatted results
fprintf('Country Gold Silver Bronze Total\n')
for i = 1:length(countries) % = 27
fprintf('%s %d \n', countries(i, :), results (i,:));
end
end
Can I print a matrix & string row by row? Please help!
EDIT: We are not allowed to use a table. πŸ™

Best Answer

You can change your function like this
function [ ] = print_country_results(countries,results)
% prints formatted results
fprintf('Country\tGold\tSilver\tBronze\tTotal\n')
for i = 1:length(countries) % = 27
fprintf('%s\t%d\t%d\t%d\t%d\n', countries(i, :), results (i,:));
end
end
Output:
Country Gold Silver Bronze Total
AUS 2 1 0 3
AUT 4 6 6 16
BLR 1 1 1 3
CAN 14 7 5 26
CHN 5 2 4 11
CRO 0 2 1 3
CZE 2 0 4 6
EST 0 1 0 1
FIN 0 1 4 5
FRA 2 3 6 11
GBR 1 0 0 1
GER 10 13 7 30
ITA 1 1 3 5
JPN 0 3 2 5
KAZ 0 1 0 1
KOR 6 6 2 14
LAT 0 2 0 2
NED 4 1 3 8
NOR 9 8 6 23
POL 1 3 2 6
RUS 3 5 7 15
SLO 0 2 1 3
SUI 6 0 3 9
SVK 1 1 1 3
SWE 5 2 4 11
USA 9 15 13 37
XXX 1 0 2 3