Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - sort cell array of objects by property

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

like image 922
Kieran Harper Avatar asked May 13 '13 04:05

Kieran Harper


People also ask

How do you sort a cell array in MATLAB?

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.

How do I sort a cell array in descending order MATLAB?

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.

How do you sort an entire array in MATLAB?

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.

How do you create an array of objects in MATLAB?

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 .


1 Answers

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);
like image 148
Jonas Avatar answered Sep 28 '22 06:09

Jonas