Matlab - sort cell array of objects by property

我的未来我决定 提交于 2019-12-01 05:05:51

问题


Suppose I had a class named Foo, with a datenum property named DateTime. If I had a cell array collection of Foo objects, how would I sort that according to each object's DateTime property?

I have seen references to overloading the sort method and working with arrays of objects, however I'm using a cell array due to dynamic sizing and those instructions aren't holding up. Anybody got some suggestions? Cheers


回答1:


The simplest approach is to extract the time-values into a vector, sort that, and use the new order to sort the original array.

%# extract DateTime from the cell array fooCell
dateTime = cellfun(@(x)x.DateTime, fooCell);

[~,sortIdx] = sort(dateTime);

%# reorder fooCell
fooCell = fooCell(sortIdx);


来源:https://stackoverflow.com/questions/16515031/matlab-sort-cell-array-of-objects-by-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!