MATLAB: Num2str or str2num

num2strstr2num

I am trying to make a table of numbers with corresponding names for example: names and grade table sorted by the number
Bob 97
Joe 87
Sally 88
How do i setup a variable to equal something like a= Bob 97 so when i go to do the fprintf it will sort by the numbers in the second column and leave the corresponding names to the number in the first column
final table should look like:
Name Grade
Joe 87
Sally 88
Bob 97

Best Answer

Ryan, if you can read in from your input (say, with textscan) and stuff the name into a cell array and stuff the numbers into a double array, then you can sort the double array and sort the cell array the same way, like in this (untested) code:
% Create sample data:
names = {'Bob'; 'Joe'; 'Sally'}
grades = [97 87 88]
% Now sort by ascending grade number:
[sortedGrades sortOrder] = sort(grades, 'ascend');
% Sort the names the same way.
sortedNames = names(sortOrder);
% Now print out to the command window.
fprintf('Name Grade\n');
for k = 1 : length(sortedGrades)
fprintf('%s %d\n', sortedNames{k}, sortedGrades(k));
end
In the command window:
names =
'Bob'
'Joe'
'Sally'
grades =
97 87 88
Name Grade
Joe 87
Sally 88
Bob 97