How can I sort a cell array according to one column's order?

Hi, I have a cell array of (50, 2), each cell in the first column contains a 4x960 matrix but the cells in the second column are 1x1 numbers. Each cell in the second column shows the rank for the matrix in the same row of the cell array. For example cell(1,1) is a 4x960 matrix and it's rank is in cell(1,2). I want to sort this cell array according to the rank(second) column, meaning that if a matrix (in the first column) has the highest rank(in the second column) and needs to be moved to the last row(descending order), it's matrix in the first column should move with it to the last row, too. Would you please help me?

Answers (1)

There may be a conflict in what you define to be of 'descending order':
"if a matrix (in the first column) has the highest rank(in the second column) and needs to be moved to the last row(descending order), it's matrix in the first column should move with it to the last row, too"
This example goes with the "first row will have the smallest rank" way:
A; % this is the input cell array
[ranks_ordered, idx] = sort(cell2mat(A(:,2)));
B = A(idx,:);
sort returns the sorting indices as the second output argument, which is then used to re-sort the original cell array.

4 Comments

Thank you so much for your help, I have some questions, will this change the nature of the second column which is a cell array to a matrix?
[ranks_ordered, idx] = sort(cell2mat(A(:,2)));
and how can I use the idx to sort the first column too, again cell2mat?is it possible, and which part defines the descending order? Will it be easier if I just move the highest rank and it's matrix in the same row to the last row of the cell array? Since I just need this to happen.
Thank you so much again.
ranks_ordered will be a numeric array from the rank values (second column of the original cell array), so the type changes there, but the original data is unchanged, it stays a cell array.
Check what B gives once you run the code. A(idx,:) indexes the rows (first 'coordinate') of A, and does this to the whole contents of the rows, explained here.
Thanks a ton for everything.

Sign in to comment.

Categories

Tags

Asked:

on 31 Oct 2016

Commented:

on 31 Oct 2016

Community Treasure Hunt

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

Start Hunting!