user3161383
user3161383

Reputation: 41

Sorting a cell array of matrices based on numerical value in each matrix?

I am working on a coding project and ran into a roadblock. I have a cell array of 1x3 matrices. (1,1) encodes the value to sort by, (1,2) and (1,3) encode coordinates that i need for reference later. Is there any way to sort the cell array by the (1,1) values in each matrix within the larger cell array?

CombList = {[1,1,1], [5,1,2];
            [4,1,3], [3,1,2];
            [2,1,4], [2,1,3]};

I would like to sort by the first values in each matrix within the cell array. Ideally, it would return:

CombList = [1,1,1], [2,1,3];
           [2,1,4], [3,1,2];
           [4,1,3], [5,1,2]};

...once sorted:)

Thank you!

Upvotes: 4

Views: 179

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112679

Zany one-liner based on sortrows:

CombList = reshape(mat2cell(sortrows(cell2mat(reshape(CombList,[],1))),ones(numel(CombList),1),numel(CombList{1})),2,[]).';

Upvotes: 0

Stewie Griffin
Stewie Griffin

Reputation: 14939

I believe the following should work. The result will be a numeric array, hope that will work for you.

CombList = {[1,1,1], [5,1,2];
            [4,1,3], [3,1,2];
            [2,1,4], [2,1,3]}

CombMat = cell2mat(CombList);
CombMat(:, 1:3) = sortrows(CombMat(:, 1:3));
CombMat(:, 4:6) = sortrows(CombMat(:, 4:6));

You can use mat2cell to get convert it back to a cell array, like this:

CombCell = mat2cell(CombMat, [1 1 1], [3 3])

Upvotes: 0

Related Questions