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
You can convert your cell array into a matrix using CELL2MAT, sort according to the column you choose using SORTROWS, and then convert the matrix back to a cell array using MAT2CELL. Note that there are certain limitations on the cell array for being able to use the CELL2MAT function.
The ability to sort a cell-array using the 'descend' option is not available with the SORT command in MATLAB. As a workaround, to create a cell array of descending order, perform the operations FLIPLR and FLIPUD on the output of SORT.
B = sort( A ) sorts the elements of A in ascending order. If A is a vector, then sort(A) sorts the vector elements. If A is a matrix, then sort(A) treats the columns of A as vectors and sorts each column.
Build Arrays in the ConstructorTo preallocate the object array, assign the last element of the array first. MATLAB® fills the first to penultimate array elements with the ObjectArray object. After preallocating the array, assign each object Value property to the corresponding value in the input array F .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With