How do I identify elements in a table/matrix and sort them in descending order?

1 view (last 30 days)
Hello!
I've got an matrix/table with given names to each row and column (1,2 ... 10).
Each element has a diffrent number, for example the element N of Row 1 and Column 4 is 52, and Row 4 and Column 7 is 22 and so on.
I want to identify for each (r,c) element number and then put the results in a table where it identifes like this:
(1,4) = 52
(4,7) = 42
and so on...
The purpose is to do this with all types of possible (r,c) and each element and then rank them in descending order.
Any tips?
Example:
1 2 3 4 5 6 7 8 9 10 (col)
1 N N N N N N N N N N
2 N N N N N N N N N N
3 N N N N N N N N N N
4 N N N N N N N N N N
5 N N N N N N N N N N
6 N N N N N N N N N N
7 N N N N N N N N N N
8 N N N N N N N N N N
9 N N N N N N N N N N
10 N N N N N N N N N N
(row)

Answers (1)

Voss
Voss on 21 Oct 2023
Edited: Voss on 21 Oct 2023
M = magic(5) % some matrix
M = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
[v,idx] = sort(M(:),'descend');
[r,c] = ind2sub(size(M),idx);
result = [r, c, v]
result = 25×3
5 3 25 1 2 24 2 1 23 3 5 22 4 4 21 3 4 20 4 3 19 5 2 18 1 1 17 2 5 16
  2 Comments
Aron
Aron on 21 Oct 2023
Thanks!
And if 1,2,3 .. 10 was replaced by letters (A,B,C ... n). How do make that work? :D
Voss
Voss on 21 Oct 2023
T = array2table(magic(5)); % some table with row and variable/column names
T.Properties.RowNames = num2cell('A':'E');
T.Properties.VariableNames = num2cell('J':'N');
disp(T)
J K L M N __ __ __ __ __ A 17 24 1 8 15 B 23 5 7 14 16 C 4 6 13 20 22 D 10 12 19 21 3 E 11 18 25 2 9
[v,idx] = sort(T{:,:}(:),'descend');
[r,c] = ind2sub(size(T),idx);
row_names = T.Properties.RowNames(:);
col_names = T.Properties.VariableNames(:);
result = table(row_names(r), col_names(c), v)
result = 25×3 table
Var1 Var2 v _____ _____ __ {'E'} {'L'} 25 {'A'} {'K'} 24 {'B'} {'J'} 23 {'C'} {'N'} 22 {'D'} {'M'} 21 {'C'} {'M'} 20 {'D'} {'L'} 19 {'E'} {'K'} 18 {'A'} {'J'} 17 {'B'} {'N'} 16 {'A'} {'N'} 15 {'B'} {'M'} 14 {'C'} {'L'} 13 {'D'} {'K'} 12 {'E'} {'J'} 11 {'D'} {'J'} 10

Sign in to comment.

Categories

Find more on Tables in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!