How to click and sort a header in uiTable?
10 views (last 30 days)
Show older comments
I would like to sort the columns in a table by clicking on the column header I want to sort.
Is there a way to click/select the headers and sort the column in uitable?
0 Comments
Answers (1)
Rajanya
on 26 Nov 2024 at 12:13
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:
data = rand(5, 3); % Random data for demonstration in a table with 3 columns
function sortTable(tableHandle, columnIndex)
% Get the table data
data_ = get(tableHandle, 'Data'); % Data is initialized to data
% Sort the data based on the selected column
[~, sortIdx] = sort(data_(:, columnIndex));
sortedData = data_(sortIdx, :);
% Update the table with sorted data
set(tableHandle, 'Data', sortedData);
end
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:
data = rand(5, 3); % Similarly, random data for demonstration
function sortTable(src, event)
% Get the table data and column index
data_ = get(src, 'Data'); %Data is initialized with data
colIndex = event.Indices(2);
% Similarly, sort the data based on the selected column
[~, sortIdx] = sort(data_(:, colIndex));
sortedData = data_(sortIdx, :);
% Update the table with sorted data
set(src, 'Data', sortedData);
end
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 uicontrol
doc uitable
doc CellSelectionCallback
doc ButtonDownFcn
Thanks.
0 Comments
See Also
Categories
Find more on Shifting and Sorting Matrices 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!