Hi,
I have a integer matrix which I know each row contain a certain value.
I would like to sort each row of that matrix in the way this value will always be in front / first position of the row.
The other values order doesn't matter.
For example with a constant value equal to 8 :
M8 = [7 8 5;...
8 7 3;...
4 8 3;...
5 8 4];
I would like in return of such a function
sorted_M8 = [8 7 5;...
8 7 3;...
8 4 3;...
8 5 4];
What is the quickest way to do this in Matlab ?
Thank you, best.
Nicolas

 채택된 답변

David Hill
David Hill 2020년 4월 3일

0 개 추천

sorted_M8=M8';
sorted_M8(ismember(M8',8))=M8(:,1);
sorted_M8=sorted_M8';
sorted_M8(:,1)=8;

댓글 수: 3

Nicolas Douillet
Nicolas Douillet 2020년 4월 3일
편집: Nicolas Douillet 2020년 4월 3일
Ok, pretty good, thank you. I also had a similar solution :
Mt = M8';
f = Mt ~= 8;
M8 = Mt(f(:));
M8 = cat(2,8*ones(size(Mt,2),1),reshape(M8,[2,size(Mt,2)])'); % 2 because I forgot to say size(T,2) = 3 always
but still keeping the hope this could be done in one single line of code.
Two lines.
sorted_M8=ismember(M8,8).*M8(:,1)+~ismember(M8,8).*M8;
sorted_M8(:,1)=8;
Nicolas Douillet
Nicolas Douillet 2020년 4월 3일
Yeah good, thanks again. The only thing I try to avoid in general is to mix logical class objects with double class objects in computation.

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

추가 답변 (0개)

카테고리

도움말 센터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