Sort an array of cells by the first element of each cell

My problem is how to sort an array of cells, considering only the first element of each cell in this vector:

array_A={[3 1 5] [1 6 2] [2 4 1]}

I want to sort array_A, the first element of each cell as follows:

array_A={[*1* 6 2] [*2* 4 1] [*3* 1 5]}

Do you have any idea on how I can solve this problem so that it can be done recursively for thousands of cells?

+3
source share
1 answer

The simplest one can be simply linked array_Ato create a numerical array and sort it based on this. If the vectors are long or of different lengths, you can first extract the first element of each element of the cell array and sort it.

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);
+4
source

Source: https://habr.com/ru/post/1776562/


All Articles