Sorting a DenseMatrix object

239 views
Skip to first unread message

davide...@googlemail.com

unread,
Nov 16, 2015, 11:45:55 AM11/16/15
to Scala Breeze
Hi there,
I am using Breeze library for a machine learning project.
I have the need to sort a DenseMatrix based on the content of the first column.
Is there a class/function which would allow me to do that?

Many thanks,
Davide

David Hall

unread,
Nov 16, 2015, 11:49:07 AM11/16/15
to scala-...@googlegroups.com
I don't think there's anything built in to help you with that. I have aspirations of something like dm(*, ::).sortBy(r => r(0)), but that doesn't exist just yet.

For now, probably (0 until dm.rows).map(dm(_, ::)).sortBy(r => r(0))

-- David

--
You received this message because you are subscribed to the Google Groups "Scala Breeze" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-breeze...@googlegroups.com.
To post to this group, send email to scala-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/scala-breeze/96f50df3-1381-4215-833a-cae810f3a087%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

davide...@googlemail.com

unread,
Nov 25, 2015, 12:47:30 PM11/25/15
to Scala Breeze
Hi David,
thanks for prompt reply and sorry for my late reply :).

I think I sorted it out creating a function which converts the DenseMatrix to a List of DenseVector, sorts the DenseVectors and then it re-converts the List of DenseVectors back to a DenseMatrix.
The code snippet is below, i still need to test it properly though (just run a quick test as of today).

I am new with scala, so I am not sure if this is the best way.

object sortDenseMatrix {

 
def apply(inputMatrix: DenseMatrix[Double], colIndex: Int): DenseMatrix[Double] = {

    val sortingList
: List[DenseVector[Double]] = (0 until inputMatrix.rows).map(i => inputMatrix(i,::).t).toList.sortBy {x => x(0)}
    val outputMatrix
= DenseMatrix(sortingList.map(_.toArray):_*)                                                            
   
   
return outputMatrix
 
 
}
}


Davide

David Hall

unread,
Nov 25, 2015, 12:52:45 PM11/25/15
to scala-...@googlegroups.com
looks great. the .toList is probably unnecessary, though.

davide...@googlemail.com

unread,
Nov 26, 2015, 6:58:37 AM11/26/15
to Scala Breeze
Thanks for the advice David :)
Reply all
Reply to author
Forward
0 new messages