I created a cell array in Octave. Some columns contain floats, and some columns contain strings. I am able to sort the cell array by a column of strings (say col #4), using this command:
sortrows (mycellarray, 4);
But if the column I want to sort by is a column of floats, then I get this error message:
error: sort: only cell arrays of character strings may be sorted
Does anyone know how to sort a cell array, by a column of floats?
By default, the SORT function will sort values in ascending order using the first column in array. Use the optional arguments sort_index and sort_order to control which column to sort by, and the order to sort by (ascending or descending).
Accepted Answer 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.
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.
Convert the column with float values to a vector, sort it and get the sorting index. Then you can apply this index to your cell array.
mycellarray = {'a',1,0.5; 'b',2,0.1; 'c',3,4.5; 'd',4,-3.2};
vector2sort=cell2mat(mycellarray(:,3));
[~,idx] = sort(vector2sort)
mycellarraysorted = mycellarray(idx,:);
In some versions of Octave, however, the tilde ~
operator is not defined. In that case:
vector2sort = mycellarray(:,3);
[dummy,idx] = sort(vector2sort);
mycellarraysorted = mycellarray(idx,:);
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