Hi, I need to sort a matrix elementwise and get the results to a single vector without losing the index of each element.
For example,
A = [3, 4 ; 6, 2]
The sorted vector should be ,
B = [2;3;4;6]
without losing the information of each and every element in the original matrix.
Thank you.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2019년 10월 21일

1 개 추천

A = [3, 4 ; 6, 2];
[m,~] = size(A);
[B,i] = sort(A(:));
index = [mod(i-1,m) + 1, ceil(i/m)];

댓글 수: 1

Gayan Lankeshwara
Gayan Lankeshwara 2019년 10월 21일
Hi Andrei,
I tried the code and this is what I wanted.
Thank you.

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

추가 답변 (1개)

Stephan
Stephan 2019년 10월 21일

1 개 추천

B = sort(reshape(A,[],1))

댓글 수: 3

Gayan Lankeshwara
Gayan Lankeshwara 2019년 10월 21일
Hi Stephan,
Thank you for your answer.
But I actually need is something like this.
A = [3, 4 ; 6, 2]
The sorted vector should be ,
B = [2;3;4;6]
without losing the information of each and every element in the original matrix.
After I sorted the matrix and put the elements in a vector, I need to find the original index for each and every element in the sorted vector.
For example, in B=[2;3;4;6]
I need to tell element 6 is the A(2,1) element.
Actually this is kind of sorting with preserving the index.
If I just sort it, I cannot backtrack the original index of the each and every element.
Thanks.
[B, idx] = sort(reshape(A,[],1))
[row,col] = ind2sub([size(A,1), size(A,2)],idx)
Gayan Lankeshwara
Gayan Lankeshwara 2019년 10월 21일
Hi Stephan,
This is really what I needed and the inbuilt in2sub function is more powerful I guess.
Thanks.

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

카테고리

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

제품

릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by