Sorting an array of cells by the first element of each cell
My problem is in how to sort an array of cells con开发者_如何转开发sidering only the first element of each cell in that vector:
array_A={[3 1 5] [1 6 2] [2 4 1]}
I want to sort array_A, by the first element of each cell like this:
array_A={[*1* 6 2] [*2* 4 1] [*3* 1 5]}
Do you have any idea on how can I solve this, in a way that it can be done recursively for thousands of cells?
The easiest might just be to catenate array_A
to create a numeric array and sort based on that. If the vectors are long, or of different lengths, you may want to extract the first element of each element of the cell array first and sort that.
In other words:
%# extract the first number from each element of array_A
firstElement = cellfun(@(x)x(1),array_A);
%# sort (the ~ discards the first output argument of sort)
[~,sortIdx] = sort(firstElement);
%# sort array_A using the proper sort order
array_A_sorted = array_A(sortIdx);
精彩评论