Eigen: select columns with N largest norm

The following code selects columns with N largest norm. The output should be

All data and its norm:
data[0] = ( 68.0375 -21.1234) norm = 71.2412
data[1] = (56.6198 59.688) norm = 82.2707
data[2] = ( 82.3295 -60.4897) norm = 102.162
data[3] = (-32.9554 53.6459) norm = 62.9599
data[4] = (-44.4451 10.794) norm = 45.737
data[5] = (-4.52059 25.7742) norm = 26.1676
data[6] = (-27.0431 2.68018) norm = 27.1756
data[7] = (90.4459 83.239) norm = 122.919
data[8] = (27.1423 43.4594) norm = 51.2389
data[9] = (-71.6795 21.3938) norm = 74.804
Selected data with 3largest norm:
data[0] = (90.4459 83.239) original index = 7
data[1] = ( 82.3295 -60.4897) original index = 2
data[2] = (56.6198 59.688) original index = 1

#include <Eigen/Core>;
#include <iostream>;
#include <vector>;

int main()
{
	int dimData = 2;
	int numData = 10;
	int numDataSub = 3;
	Eigen::MatrixXd m = 100.0*Eigen::MatrixXd::Random(dimData, numData);
	Eigen::MatrixXd mSub = Eigen::MatrixXd::Zero(dimData, numDataSub);
	Eigen::VectorXd mNorm = m.colwise().norm();
	std::vector<int>; indexMax(numDataSub);

	std::cout << "All data and its norm:" << std::endl;
	for(int n = 0; n < numData; ++n)
	{
		std::cout << "	data[" << n << "] = (" << m.col(n).transpose() << ")	norm = " << mNorm(n) << std::endl;		
	}

	// retrieve columns whose norm  is top numDataSub
	for(int n = 0; n < numDataSub; ++n)
	{
		mNorm.maxCoeff(&amp;indexMax[n]);
		mNorm(indexMax[n]) = 0.0;
		mSub.col(n) = m.col(indexMax[n]);
	}
	std::cout << "Selected data with " << numDataSub << "largest norm:" << std::endl;
	for(int n = 0; n < numDataSub; ++n)
	{
		std::cout << "	data[" << n << "] = (" << mSub.col(n).transpose() << ")	original index = " << indexMax[n] << std::endl;		
	}

	return 0;
}
Advertisements

One thought on “Eigen: select columns with N largest norm

  1. Pingback: Eigen: select columns with N largest norm 2 | charmie11

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s