Filter löschen
Filter löschen

Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

Matrix manipulation using sort function in matlab

1 Ansicht (letzte 30 Tage)
prashanth
prashanth am 25 Apr. 2014
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
This first matrix table1 contains normalized values for 5 names.I need to perform some operations on this matrix and I have to obtain second matrix as shown in table2.
Diagonal elements of table2 should obtained by giving rank(ordinal value) to each value.That means highest element is given 5th rank and next 4th 3rd and so on.
Remaining elements of table obtained by giving rank to each value starting from 4 because only 4 elements remaining. Because already we are given rank to diagonal elements.Zero should be kept as it is.Suppose take table1 as A matrix and table2 as B matrix.
OPERATION1:For diagonal elements
B(1,1)=5(first largest element)
B(2,2)=1(5th largest element)
B(3,3)=4(4th largest element)
B(4,4)=2(2nd largest element)
B(5,5)=3(3rd largest element)
OPERATION2:For remaining elements
B(1,2)=3(2nd largest element)
B(1,3)=4(1st largest element)
B(1,4)=1(4th largest element)
B(1,5)=2(3rd largest element)
And so on..
Table1:
1.0000 0.2727 0.3182 0.0455 0.2727
0.2727 0.2727 0 0 0
0.3182 0 0.4545 0.1818 0
0.0455 0 0.1818 0.2727 0.0909
0.2727 0 0 0.0909 0.3636
Source code:
for i = 1:5
for j = 1:5
if i == j
[~, ii] = sort(diag(y));
[~, jj] = sort(ii);
table2 = diag(jj);
elseif y(i,j)==0
table2(i,j)=0;
else
[~, ij] = sort(y);
[~, ij] = sort(ij);
table2 = ij;
end
end
end
I got this output for above code
5 0 0 0 0
0 1 0 0 0
0 0 4 0 0
0 0 0 2 0
0 0 0 0 3
But i need below output. Table2:
5 3 4 1 2
4 1 0 0 0
4 0 4 3 0
2 0 4 2 3
4 0 0 3 3

Antworten (1)

prashanth
prashanth am 25 Apr. 2014
E = logical(eye(size(table1))); % create a mask for the two different rules
% rule 1: diagonal elements first
table2 = zeros(size(table1)); % create result matrix
[~,jj] = sort(table1(E));
[~,ii] = sort(jj);
table2(E) = ii; % assign rank of diagonal elements
% rule 2: rest of the matrix
E = ~E;
B = reshape(table1(E),size(table1,1)-1,size(table1,2))'; % B is the matrix of table1 without diagonal elements
[~,jj] = sort(B,2); % sort along column dimension,
[~,ii] = sort(jj,2);
table2 = table2'; % matlab is column-major, so you have to transpose the dest matrix before putting in the elements
table2(E) = reshape(ii',[],1);
table2 = table2'; % transpose back, done.
% treat zeros apart: 0 has rank 0
table2(table1==0) = 0;

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by