2016-10-03 22 views
1

如何將動態矩陣的列增加1,作爲就地操作(不創建副本/中間體)?本徵增量一列

嘗試:

#include <Eigen/Dense> 
#include <iostream> 
#include <stdint.h> 
int main(void){ 
    Eigen::MatrixXf A; 
    A = Eigen::MatrixXf::Random(3, 5); 
    std::cout << A << std::endl << std::endl; 
    A.col(1) = A.col(1)*2; //this works. 
    A.col(1) = A.col(1) + 1; //this doesn't work. 
    std::cout << A << std::endl; 
} 

回答

2

我找到了一種方法來做到這一點。但我不知道手術是否到位。

這類似於eigen: Subtracting a scalar from a vector

#include <Eigen/Dense> 
#include <iostream> 
int main(void){ 
    Eigen::MatrixXf A; 
    A = Eigen::MatrixXf::Random(3, 5); 
    std::cout << A << std::endl << std::endl; 

    A.col(1) = A.col(1)*2; 
    A.col(1) = A.col(1) + Eigen::VectorXf::Ones(3); 
    std::cout << A << std::endl; 
} 

的另一種方法是使用陣列操作。這種方式似乎更好(我猜)。

https://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html

#include <Eigen/Dense> 
#include <iostream> 
int main(void){ 
    Eigen::MatrixXf A; 
    A = Eigen::MatrixXf::Random(3, 5); 
    std::cout << A << std::endl << std::endl; 

    A.array() += 1; 
    A.col(1).array() += 100; 

    std::cout << A << std::endl; 
} 
+2

使用'陣列()'方法是什麼,我會推薦。如果您主要在做元素操作,請考慮從頭開始將'A'存儲爲'Eigen :: ArrayXXf'。稍後您仍然可以通過'matrix()'方法訪問'A'作爲矩陣。 – chtz