필터 지우기
필터 지우기

Finding sorted rows in a matrix

조회 수: 2 (최근 30일)
Marco Gaetani d'Aragona
Marco Gaetani d'Aragona 2021년 3월 20일
댓글: the cyclist 2021년 3월 21일
Hi,
I need to know which rows of a matrix are sorted in ascending without using the "for" cycle. For instance, if i have:
outsx = [
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3]
i want a vector containing indexes of which rows are sorted in ascending order. In this case.
ii= [1 4 5 7 8 9]
Thank you in advance

답변 (3개)

the cyclist
the cyclist 2021년 3월 20일
For my current understanding of what you want, I believe this works:
ii = find(diff(outsx,[],2)>=0)
  댓글 수: 2
Jan
Jan 2021년 3월 20일
I assume an all() is wanted:
ii = find(all(diff(outsx,[],2) >= 0, 2))
the cyclist
the cyclist 2021년 3월 21일
Yes, thanks for catching that

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


the cyclist
the cyclist 2021년 3월 20일
편집: the cyclist 2021년 3월 20일
outsx = [
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3];
ii = find(outsx(:,2)>=outsx(:,1))
ii = 6×1
1 4 5 7 8 9
  댓글 수: 1
Marco Gaetani d'Aragona
Marco Gaetani d'Aragona 2021년 3월 20일
Hi,
I would need a more general formulation, cosidering matrixes with different number of rows and columns

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


Star Strider
Star Strider 2021년 3월 20일
Two approaches:
for k = 1:size(outsx,1)
TF(k,:) = issorted(outsx(k,:),2,'ascend')
end
Result = find(TF)
TF = outsx(:,2) >= outsx(:,1);
Result = find(TF)
both producing:
Result =
1
4
5
7
8
9
.
  댓글 수: 2
Marco Gaetani d'Aragona
Marco Gaetani d'Aragona 2021년 3월 20일
Hi,
I need to perform this check for matrixes nxm, so I need a faster procedure without employing for cycles.
the cyclist
the cyclist 2021년 3월 20일
FYI, just because code has a for loop does not necessarily mean it is slower than other solutions.
Finding a solution that works is the first step (partly to verify that the solution does what you want), and then thinking about readability and optimization follows.

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

카테고리

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