【发布时间】:2014-08-04 08:38:09
【问题描述】:
我有一个包含零行的矩阵。我想删除零行。矩阵为 Nx3。我所做的很简单。我创建std::vector,其中每三个元素代表一行,然后将其转换为Eigen::MatrixXd。有没有删除零行的优雅方法?
#include <iostream>
#include <vector>
#include <Eigen/Dense>
Eigen::MatrixXd VecToMat(const std::vector<double> vec)
{
int rows(vec.size()/3) , cols(3);
Eigen::MatrixXd temp( rows , cols);
int count(0);
for ( int i(0); i < rows; ++i)
{
temp(i,0) = vec[count];
temp(i,1) = vec[count+1];
temp(i,2) = vec[count+2];
count += 3;
}
return temp;
}
Eigen::MatrixXd getNewMat(Eigen::MatrixXd& Z)
{
std::vector<double> vec;
for ( int i(0); i < Z.rows(); ++i)
{
if ( (Z(i,0) && Z(i,1) && Z(i,2)) != 0 ){
vec.push_back(Z(i,0));
vec.push_back(Z(i,1));
vec.push_back(Z(i,2));
}
}
Eigen::MatrixXd temp = VecToMat(vec);
return temp;
}
int main()
{
Eigen::MatrixXd Z(5,3);
Z.setOnes();
Z(0,0) = 0;
Z(0,1) = 0;
Z(0,2) = 0;
Z(1,0) = 0;
Z(1,1) = 0;
Z(1,2) = 0;
Z(2,0) = 0;
Z(2,1) = 0;
Z(2,2) = 0;
std::cout << Z << std::endl << std::endl;
std::cout << getNewMat(Z) << std::endl;
std::cin.get();
return 0;
}
【问题讨论】:
-
您要在程序的哪一点去除零?
-
@Velthune,你是什么意思?
-
想要从 MatrixXd 或向量中删除零?
-
来自矩阵。我用矢量来四处走动。但我猜这绝对不是一种优雅的方式。
-
我看不出这个检查是如何工作的:
(Z(i,0) && Z(i,1) && Z(i,2)) != 0。如果任何一个为 0,则应返回 false。如果你想变得棘手,你想要||,而不是&&,或者你可以把它们全部写出来。或者寻找一种将行作为(数学)向量的方法,并将其与 0(数学)向量进行比较。