1
votes

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?

1
It would be much better if you used a struct array for your data: S = [OPEN{:}]. The resulting data structure is more efficient memory-wise, but also makes it easier to do certain manipulations like your sorting. - Cris Luengo
You are definitely right. Structs inside cell array is making it very hard for me to manipulate the list. - kucar

1 Answers

2
votes

Maybe you can try cellfun + getfield + sort like below

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