Search code examples
arraysmatlabstructurecell-array

Sorting a Cell Array which consists of structures in MATLAB?


Hello there, hope you are all very well.

Right now I am working on an assignment on MATLAB. I have a cell array which consists of 6 structs with 6 fields in them. The cell array looks like this:

enter image description here

Each one of the structs also looks something like this:

enter image description here

I need to sort this cell array with respect to totalCost values stored in them. I do not know if I would be able to do it just by sort function. I want each struct in the cells to remain the same after sorting. The struct which has the least totalCost is going to be the first cell in the cell array, and vice versa. Can you help me with that?


Solution

  • Maybe you can try cellfun + getfield + sort like below

    [~,I] = sort(cellfun(@(s) getfield(s,"totalCost"), OPEN));
    OPENsort = OPEN(I);