MatrixXf使用:根据输入数据,动态指定矩阵大小

如何根据输入数据,动态指定矩阵大小

方法1

在矩阵定义时根据数据大小指定矩阵大小,形如:const int NUM = (int)data.size(); Matrix<float,8,NUM> routeN; 不可行,见testMatrixXf_1()分析,如下:

int testMatrixXf_1()
{
	std::vector<float> data = {1,2,3,4};
	const int NUM = (int)data.size();//‘NUM’ was not initialized with a constant expression

	//--- 在C++中,const变量, 是不是用常量初始化均可,可以用来定义数组大小,在C中不可以;
	int array[NUM] = {1,2,3,4}; 
	cout<<" array = " << array[0] <<   array[1] <<   array[2] <<   array[3] <<endl; 

	//--- Matrix<float, size_r, size_c> size_r和 size_c的性质必须是 常量或常量表达式,常变量不行,编译阶段即通不过;
	Matrix<float,8,NUM> routeN;// NUM为常变量,编译报错

	const int NUM_2 = 4;//initialized with a constant expression
	const int NUM_1 = NUM_2;
	Matrix<float,8,NUM_1> routeN1;//NUM_1 为常量,编译通过
	for (int i=0; i<NUM_1; i++)
	{
		routeN1.col(i)<< 1,2,3,4,5,6,7,8;
	}
	cout << "routeN1 = \r\n  "  << routeN1 <<endl;

	return 0;
}

这里会涉及到C++中const量的性质,具体测试分析可参见:

C++/C中const的区别 - 不同初始化方式对C++中const量性质的影响_reason的博客-CSDN博客

方法2:

利用MatrixXf的 resize()成员函数,根据获取数据大小,先resize矩阵大小,再填充数据,见testMatrixXf_2()分析,如下:

int testMatrixXf_2()
{
	//---  对于未初始化的MatrixXf变量,行、列均为-1,取一列进行赋值时,会报段错误
	// MatrixXf routeN;
	// for (int i=0; i<NUM; i++)
	// {
	// 	routeN.col(i)<< 1,2,3,4,5,6,7,8;//Assertion `(i>=0) && (  i<xpr.cols()))' failed.,
	// }

	std::vector<float> data = {1,2,3,4};
	int NUM = ( int)data.size();//‘NUM’ was not initialized with a constant expression

	MatrixXf routeNX;
	routeNX.resize(8, NUM);//使用resize()
	cout << "routeNX..resize(8, NUM) = \r\n  "  << routeNX <<endl;

	for (int i=0; i<NUM; i++)
	{
		routeNX.col(i)<< 1,2,3,4,5,6,7,8;
	}
	cout << "routeNX - fill_value = \r\n  "  << routeNX <<endl;

	// ---resize后,MatrixXf  routeNX变成无初始化状态,各元素值随机;
	routeNX.resize(NoChange, 2);
	cout << "routeNX.resize(NoChange, 2)= \r\n  "  << routeNX <<endl;

	routeNX.resize(8, 2);
	cout << "routeNX.resize(8, 2)= \r\n  "  << routeNX <<endl;
	routeNX.resize(2, 2);
	cout << "routeNX.resize(2, 2) = \r\n  "  << routeNX <<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值