Sort cell array according to the max value in the second row
조회 수: 1 (최근 30일)
이전 댓글 표시
I wrote scripe that store data in the following format:
row1= {car1, car2, car3,....., etc}
row2 = {20, 180,500, ......., etc}
I want to sort my output as using the maximum value in the second row
I expect this output
row1={car3,car2,car1, .....do this until the end}
row2={500,180, 20,..... do this until the end}
I appreciate your help
댓글 수: 1
Image Analyst
2014년 1월 17일
Why are you using cell arrays instead of regular numerical arrays? I see no need for complicating it like that. And instead of the unclear/ambiguous "according to the max value" I think most people would say "in descending order".
채택된 답변
Azzi Abdelmalek
2014년 1월 17일
편집: Azzi Abdelmalek
2014년 1월 17일
row1= {1, 2, 3}
row2 = {20, 180,500}
a=sortrows([row1' row2'],2);
out=flipud(a(:,1))
%or
[idx,idx]= sort(cell2mat(row2),'descend')
out=row1(idx)
댓글 수: 11
추가 답변 (2개)
Image Analyst
2014년 1월 17일
If you want to use a regular numerical array instead of a cell array, you can do this:
% Create Sample data
m = randi(99, 2, 10)
[sortedValues, sortingIndexes] = sort(m(2,:), 'descend')
sorted_m = m(:, sortingIndexes)
In the command window, you'll see:
m =
81 13 63 28 95 16 95 80 42 79
90 91 10 55 96 97 49 15 91 95
sortedValues =
97 96 95 91 91 90 55 49 15 10
sortingIndexes =
6 5 10 2 9 1 4 7 8 3
sorted_m =
16 95 79 13 42 81 28 95 80 63
97 96 95 91 91 90 55 49 15 10
댓글 수: 2
Image Analyst
2014년 1월 18일
편집: Image Analyst
2014년 1월 18일
Is this solved yet? I can't tell from your comments, where you say "@Image Analyst: Thank u, I think you understand my problem quite well". Did the code solve your problem of sorting both arrays in the same order, or not?
row1 = {'car1', 'car2', 'car3'}
row2 = {20,1999,233}
[sortedValues, sortIndexes] = sort(cell2mat(row2), 'descend')
outRow1 = row1(sortIndexes)
outRow2 = row2(sortIndexes)
You didn't mark any answer as "Accepted" yet, so I'm guessing it's not working. If not, then please attach your actual m-file so we can get this solved.
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!