index problem while sort

조회 수: 13 (최근 30일)
VINAY PRAJAPATI
VINAY PRAJAPATI 2024년 2월 1일
이동: Walter Roberson 2024년 2월 1일
I am trying to sort some positive values from one array and finding the index of that.
Omega=[1.528 -1.528 0.792 -0.792];
[NN,ind]=sort(Omega(Omega>=0));
Answer:
NN=[0.792 1.528]
but
ind=[2,1] is coming which is wrong. It should ind=[3,1].
Please help regarding this.

채택된 답변

Dyuman Joshi
Dyuman Joshi 2024년 2월 1일
편집: Dyuman Joshi 2024년 2월 1일
"ind=[2,1] is coming which is wrong."
It is correct.
The input to sort() only has 2 elements, so the expectation to get [3 1] as the output is misplaced -
Omega=[1.528 -1.528 0.792 -0.792];
Omega(Omega>=0)
ans = 1×2
1.5280 0.7920
I assume you want to get the indices of these particular values from the original array, in that case, try this -
NN=sort(Omega(Omega>=0))
NN = 1×2
0.7920 1.5280
[~,idx] = ismember(NN,Omega)
idx = 1×2
3 1
Ideally, you should use ismembertol to compare floating point numbers.
However, the values here are obtained directly from the original array via indexing, so ismember() works here.
  댓글 수: 1
VINAY PRAJAPATI
VINAY PRAJAPATI 2024년 2월 1일
이동: Walter Roberson 2024년 2월 1일
Thank you so much sir for solving the problem.

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

추가 답변 (1개)

VBBV
VBBV 2024년 2월 1일
이동: Dyuman Joshi 2024년 2월 1일
Here is another way to get the indices without overhead of using ismember function
Omega=[1.528 -1.528 0.792 -0.792];
[NN,ind]=sort(Omega)
NN = 1×4
-1.5280 -0.7920 0.7920 1.5280
ind = 1×4
2 4 3 1
ind(NN>0)
ans = 1×2
3 1

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by