Eigen二维数组列间算术操作编译失败问题咨询
Hey there! Let's figure out why that column subtraction is failing for you in Eigen 3.3.4 with Clang 5.0.1.
From what you described, the most likely culprit here is a type mismatch between your "locally zero-initialized 2D array" and the Eigen matrix columns you're trying to subtract. Here's the breakdown:
Eigen's column expressions (like data.col(i)) are strongly typed objects (specifically Eigen::Block types) designed to work with other Eigen-native types (matrices, vectors, arrays). If your zero array is a plain C++ native array (like double zero[rows][cols] = {};), Eigen has no idea how to perform arithmetic between its specialized column type and a raw C-style array—even if their shapes match perfectly. Static type checking in C++ will reject this immediately, which is why your code won't compile.
Fixes to try:
Use Eigen's built-in zero matrix instead of a native array
This is the simplest approach. Eigen has a dedicated method to create a zero-filled matrix matching your data's dimensions, which plays nicely with column operations:void do_calc(Eigen::MatrixXd data) { // Create an Eigen zero matrix with the same size as your input data Eigen::MatrixXd zero_mat = Eigen::MatrixXd::Zero(data.rows(), data.cols()); // Now column subtraction works perfectly Eigen::VectorXd first_col_diff = data.col(0) - zero_mat.col(0); // If you want to modify the original matrix's columns directly: // data.col(1) -= zero_mat.col(1); }Map your native zero array to an Eigen matrix
If you absolutely need to use a native array, you can useEigen::Mapto wrap it into an Eigen-compatible type. This lets Eigen treat the raw array as one of its own matrices:void do_calc(const Eigen::MatrixXd& data) { int rows = data.rows(); int cols = data.cols(); // Your native zero-initialized array (make sure dimensions match!) double zero_arr[10][10] = {}; // Use dynamic allocation if sizes aren't fixed // Map the native array to an Eigen matrix Eigen::Map<const Eigen::MatrixXd> zero_mat(zero_arr[0], rows, cols); // Column subtraction is now valid Eigen::VectorXd col_diff = data.col(2) - zero_mat.col(2); }
The key takeaway here is that Eigen relies on its own type system for efficient, safe operations—raw C arrays don't fit into that system without a little extra work. Even if the shapes look identical, the types have to match (or be convertible) for the compiler to accept the operation.
内容的提问来源于stack exchange,提问作者Eric Hansen

