Ask Your Question
0

How can I sort the matrix acc. to the first column?

asked 2014-12-27 09:48:07 -0600

huehue gravatar image

updated 2014-12-27 10:37:51 -0600

Guanta gravatar image

I have a Mat. I want to change the order of its rows, based on the value of their first element. So a row that begins with 1 will be placed before a row beginning with 2 etc. If two rows begin with the same number, I want to keep their original order.

Is there a simple way to achieve this ? I would be very grateful if someone help me.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
3

answered 2014-12-27 10:36:38 -0600

Guanta gravatar image

updated 2014-12-27 12:56:08 -0600

yes, with cv::sortIdx it shouldn't be too difficult and work similar to (I haven't tested it - but you should get the spirit):

//get first column
cv::Mat one = your_mat.col(0);
// sort the first column and save indices in dst
cv::Mat1i idx;
cv::sortIdx(one, idx, cv::SORT_EVERY_COLUMN + cv::SORT_ASCENDING);
// now build your final matrix
cv::Mat result(your_mat.rows, your_mat.cols, your_mat.type());
for(int y = 0; y < your_mat.rows; y++){
   your_mat.row(y).copyTo(result.row(idx(0,y)));
}
edit flag offensive delete link more

Comments

ah, cool. that really works ;)

maybe fix the constants ?

cv::SORT_EVERY_COLUMN + cv::SORT_ASCENDING

CV_ prefix and cv:: namespace are kinda xor

berak gravatar imageberak ( 2014-12-27 11:00:08 -0600 )edit

you're right, I fixed it. Thx for testing!

Guanta gravatar imageGuanta ( 2014-12-27 12:57:17 -0600 )edit
-1

answered 2016-04-15 13:18:10 -0600

muglikar gravatar image
//get first column
cv::Mat one = your_mat.col(0);
// sort the first column and save indices in dst
cv::Mat1i idx;
cv::sortIdx(one, idx, cv::SORT_EVERY_COLUMN + cv::SORT_ASCENDING);
// now build your final matrix
cv::Mat result(your_mat.rows, your_mat.cols, your_mat.type());
for(int y = 0; y < your_mat.rows; y++){
   your_mat.row(idx(0,y)).copyTo(result.row(y)); //correction here
}
edit flag offensive delete link more

Comments

Thanks! This is the right answer.

megOut gravatar imagemegOut ( 2018-03-16 11:52:59 -0600 )edit

this corriection dont work for me

marieevecyr gravatar imagemarieevecyr ( 2019-04-15 09:16:37 -0600 )edit

The idx should indeed be on the left side, although muglikars answer game me an exception. For me the correct line there was:

your_mat.row(idx(y)).copyTo(result.row(y));

This did sort correctly, the answer of Guanta (the current most upvoted answer) gave me weird sortings.

AmberElferink gravatar imageAmberElferink ( 2019-07-02 04:48:47 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2014-12-27 09:45:17 -0600

Seen: 2,816 times

Last updated: Apr 15 '16