How to click and sort a header in uiTable?
조회 수: 9 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Rajanya
2024년 11월 26일 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
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!