Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a cell array in Octave by a column of floats?

Tags:

sorting

octave

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?

like image 644
moondog Avatar asked Jan 23 '12 21:01

moondog


People also ask

How do I sort a cell array based on one column?

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).

How do you sort a cell array?

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.

How do you sort a column of a matrix 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.


1 Answers

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,:);
like image 158
yuk Avatar answered Oct 24 '22 15:10

yuk