How do I sort a matrix by absolute value and display its original value with +,- sign?

 채택된 답변

DGM
DGM 2021년 3월 29일
편집: DGM 2021년 3월 29일

2 개 추천

Consider the case for a vector:
A=randi(19,[10 1])-10
[~,idx]=sort(abs(A))
Asorted=A(idx)
For other arrays, you'll have to decide how exactly you want to sort it, and do the indexing accordingly.

댓글 수: 4

clc
clear
% generating the table of rows and columns
row = input('Enter number of rows: ');
col = input('Enter number of columns: ');
C = zeros(row ,col);
%taking values from user of matrix
for s = 1:row
for l = 1:col
str = ['Enter element in row ' num2str(s) ', col ' num2str(l) ': '];
C(s,l) = input(str);
end
end
%taking absolute values of all elements
D=abs(C);
%sorting the rows in descending order
[T,I]=sort(D,2,'descend');
This is my code. Please help me with this, Matrix C has the original input from user in +,- sign, D has the absolute value of C, T gives the sorted matrix but all in + sign ,but I want the sorted result with both +,- sign as the input given by user.
e.g C= [ 1 -8
-4 7]
D=[ 1 8
4 7]
T=[8 1
7 4]
i want the result as res= [-8 1
7 -4]
If you want to sort descending on dim2, my method becomes more cumbersome because of how the index array is organized as row vector indices instead of array indices.
% you could do this without a loop
% but this is less obfuscated
[T,idx]=sort(abs(C),2,'descend');
for r=1:row % because we're sorting on dim2
T(r,:)=C(r,idx(r,:));
end
T
If you're using a sufficiently recent version, you can just use Steven's suggestion from his answer, which is much more concise.
T=sort(C,2,'descend','comparisonmethod','abs')
For your purposes these two methods are probably both fine, but they do handle duplicate values differently.
Poorva
Poorva 2021년 3월 30일
Thank you ....I got it now and the code is working well.
[y, idx2] = sort(D,2,'descend');
sx = size(C);
index = sub2ind(sx, repmat((1:sx(1)).', 1, sx(2)), idx2);
y2 = C(index);
res=array2table(y2)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2021년 3월 30일

1 개 추천

Specify the 'ComparisonMethod' name-value pair argument.
rng default
A = randi([-10 10], 5, 5)
A = 5×5
7 -8 -7 -8 3 9 -5 10 -2 -10 -8 1 10 9 7 9 10 0 6 9 3 10 6 10 4
[values, locations] = sort(A(:), 'ComparisonMethod', 'abs');
[values.'; locations.']
ans = 2×25
0 1 -2 3 3 4 -5 6 6 7 7 -7 -8 -8 -8 9 9 9 9 10 10 10 10 10 -10 14 8 17 5 21 25 7 15 19 1 23 11 3 6 16 2 4 18 24 9 10 12 13 20 22

댓글 수: 2

DGM
DGM 2021년 3월 30일
Do you know about when that option was introduced? I'm guessing it was some time around 2018, but release notes are vague and I only know it's not in R2015b.
Poorva
Poorva 2021년 3월 30일
thank you steven ....my code is working.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

질문:

2021년 3월 29일

댓글:

2021년 3월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by