As per my information, MATLAB's ‘uitable’ does not provide built-in support for sorting columns directly by clicking on the column headers.
However, there are a couple of ways in which a similar behaviour can be achieved.
a) You can use ‘uicontrol’ buttons (e.g. pushbutton) with the ‘ButtonDownFcn’ callback, above the column headers to each column, such that when the button above a particular column is pressed, the table gets sorted based on the cell values of that column. A sample function, called when any button is pressed, can look like:
function sortTable(tableHandle, columnIndex)
data_ = get(tableHandle, 'Data');
[~, sortIdx] = sort(data_(:, columnIndex));
sortedData = data_(sortIdx, :);
set(tableHandle, 'Data', sortedData);
After creating a table and adding the buttons with the callback, it sorts the data in the table based on the ‘column button’ pressed as shown:
Table originally:
Table after ‘Column 1’ is pressed:
b) You can use ‘CellSelectionCallback’ of ‘uitable’ in case of which, the table can get sorted based on the cell values belonging to the column of the selected cell (which is not the header to the column itself). A sample function here can look like this:
function sortTable(src, event)
data_ = get(src, 'Data');
colIndex = event.Indices(2);
[~, sortIdx] = sort(data_(:, colIndex));
sortedData = data_(sortIdx, :);
set(src, 'Data', sortedData);
In this case also, the table gets sorted based on the column of the selected cell, as shown:
Table gets sorted according to ‘Column3’:
To know more about ’uicontrol’, ‘uitable’ and the app callbacks, you can refer to their respective documentation pages by executing the following commands from the MATLAB Command Window:
doc CellSelectionCallback
Thanks.