MATLAB: Problems Sorting a Table using sortrows

sortrowstable

I have this table of data I need to sort based on the values in the 'Odometer' column. Here is the code I'm using.
%%Odometer Sort Algorithm
s2 = 'Odometer';
num_cols = size(data,2);
num_rows = size(data,1);
% Finds the 'Odometer' column
% starts at 2 so header doesn't get sorted
for k = 2:1:num_cols
s1 = data{1,k};
if strcmp(s1,s2)
break
end
end
for j = 2:1:num_rows
data{j,k} = str2double(data{j,k});
end
data = sortrows(data,k);
When I run the code, I get the following error:
Error using char
Cell elements must be character arrays.
Error in sortrows>sort_cell_back_to_front (line 135)
tmp = char(x(ndx,k));
Error in sortrows (line 87)
ndx = sort_cell_back_to_front(x_sub, col);
Error in Test (line 29)
data = sortrows(data,k);
I think this is a result of the first element in the 'Odometer' column being a char. How can I properly sort the rows below the first element??

Best Answer

You kind of inadvertantly answered your question in your title.
The simplest way is to actually use a table instead of a cell array. tables are a lot easier to work with as well.
%convert cell array into table:
datatable = cell2table(data(2:end, :), 'VariableNames', matlab.lang.makeValidName(data(1, :)));
%sort rows according to odometer column:
sortedtable = sortrows(datatable, 'Odometer')
That's all that is needed. No searching for the odometer column. The table knows where it is.
If you don't want to use a table and want to keep using a cell array, then sort your rows ignoring the first one:
sorteddata = [data(1, :); sortrows(data(2:end, :), k)];
Note: the loop for finding the odometer column wasn't needed, this would have achieved the same:
k = find(strcmp(data(1, :), 'Odometer'));