C++ 特征矩阵的就地元素类型转换
我想将整数矩阵转换为浮点矩阵,这样:C++ 特征矩阵的就地元素类型转换,c++,eigen,C++,Eigen,我想将整数矩阵转换为浮点矩阵,这样: 数据不会被复制 没有分配新内存 数据的新浮点视图是可变的 最新尝试: #include "Eigen/Eigen" #include <iostream> int main(){ using namespace Eigen; MatrixXi x(3,3); x.fill(0); double* ptr_x = (double*)(x.data()); Map<MatrixXd> y(ptr_x
#include "Eigen/Eigen"
#include <iostream>
int main(){
using namespace Eigen;
MatrixXi x(3,3);
x.fill(0);
double* ptr_x = (double*)(x.data());
Map<MatrixXd> y(ptr_x, x.rows(), x.cols());
x(0,0) = 100;
y = x.cast<double>();
y(1,1) = 0.5f;
std::cout << y << "\n";
}
以下内容未编译:
#include "Eigen/Eigen"
#include <stdint.h>
#include <iostream>
int main(){
using namespace Eigen;
MatrixXi x(3,3);
x.fill(0);
float* ptr_x = (float*)(x.data());
Map<MatrixXd> y(ptr_x, x.rows(), x.cols());
x(0,0) = 100;
y(1,1) = 0.5f;
y = x.cast<float>();
std::cout << y << "\n";
}
#包括“本征/本征”
#包括
#包括
int main(){
使用名称空间特征;
MatrixXi x(3,3);
x、 填充(0);
float*ptr_x=(float*)(x.data());
映射y(ptr_x,x.rows(),x.cols());
x(0,0)=100;
y(1,1)=0.5f;
y=x.cast();
std::cout在确定了类型之后,下面的代码最终起作用
节目:
#include "Eigen/Eigen"
#include <iostream>
int main(){
using namespace Eigen;
MatrixXi x(3,3);
x.fill(0);
float* ptr_x = (float*)(x.data());
Map<MatrixXf> y(ptr_x, x.rows(), x.cols());
x << 1,2,3,4,5,6,7,8,9;
y = x.cast<float>();
y /= 2;
std::cout << y << "\n";
}
首先,您不能将其转换为double(不分配更多空间)矩阵,因为double是内存中的8字节,而int是4字节
我认为您可以简单地向原始矩阵投射一个浮点指针
#include "Eigen/Eigen"
#include <iostream>
int main()
{
using namespace Eigen;
MatrixXi x(3, 3);
x.fill(2);
MatrixXf* float_ptr = (MatrixXf*) &x;
float_ptr->operator()(2,2) = 42.1f;
std::cout << "float cast(2,2): " <<
float_ptr->operator()(2, 2) << std::endl;
std::cout << "float cast(1,1): " <<
float_ptr->operator()(1, 1) << std::endl;
std::cout << "x(1,1): " << x(1, 1) << std::endl;
}
因此…只要使用此指针,分配的对象将充当浮点矩阵,但请记住,不能将“x”当作浮点矩阵使用,因为使用“x”的任何函数调用都会导致分配的内存被解释为整数矩阵
例如:由于我们已将原始(2,2)从int更改为float,如果您尝试使用“x”检索它,您将看到类似的内容
.
.
.
std::cout << "float cast(2,2): " <<
float_ptr->operator()(2, 2) << std::endl;
std::cout << "x(2,2): " << x(2, 2) << std::endl;
x.data()
仅为4*9字节,而y
需要8*9字节的memory@chtz你是对的。在修复了两种类型之后,它就起作用了。你真的应该删除那个尖刻的so评论:)1小时,让so弄明白。:)过一会儿。反正没有人会访问这个帖子。我承认延迟是奇怪的。问题很简洁,所以我很惊讶没有人c很快就搞定了。我想是运气不好。我的评论原来是个笑话。哈哈。没有从整数42.1转换成浮点42.1。还有,那是不是由Eigen记录的castMatrixXf*float\u ptr=(MatrixXf*)&x;
?
#include "Eigen/Eigen"
#include <iostream>
int main()
{
using namespace Eigen;
MatrixXi x(3, 3);
x.fill(2);
MatrixXf* float_ptr = (MatrixXf*) &x;
float_ptr->operator()(2,2) = 42.1f;
std::cout << "float cast(2,2): " <<
float_ptr->operator()(2, 2) << std::endl;
std::cout << "float cast(1,1): " <<
float_ptr->operator()(1, 1) << std::endl;
std::cout << "x(1,1): " << x(1, 1) << std::endl;
}
float cast(2,2): 42.1
float cast(1,1): 2.8026e-45 (which is ~2)
x(1,1): 2
Press any key to continue . . .
.
.
.
std::cout << "float cast(2,2): " <<
float_ptr->operator()(2, 2) << std::endl;
std::cout << "x(2,2): " << x(2, 2) << std::endl;
float cast(2,2): 42.1
x(2,2): 1109943910