Search code examples
c++eigen3

Eigen compund addition gives wrong result


I declared two Eigen::RowVectorXd variables in the program as below. I get wrong results in the compound addition statement sdf_grad+=gradval. Only the first two elements are added and the rest of elements in the sdf_grad vector become 1e19. I don't have any clue why it is happening. Please Help.

Eigen::RowVectorXd sdf_grad(24);
Eigen::VectorXd stress_dof = get_stress_dof();
Eigen::VectorXd strain_dof = get_strain_dof();


for(unsigned int i=0;i!=qn.size(); i++)
{
    for(unsigned int j=0; j!=qn.size();j++)
    {
        double sval = qn[i];
        double tval = qn[j];
        if(!m_shape->m_set_coordinate)
               m_shape->add_coordinates(this->get_xcoords(),this->get_ycoords());
        m_shape->update_shapefn(sval,tval);
        Eigen::MatrixXd Bs = get_bsmat_local(i,j);
        Eigen::Vector3d stress = Bs*stress_dof;
        Eigen::MatrixXd Bd = get_bmat(sval,tval);
        Eigen::Vector3d strain = Bd* strain_dof;


        Eigen::Vector3d cnfn = m_material->get_constitutive_function(stress,strain);
        auto WxJ  = qw[i] * qw[j] * m_shape->get_detJ();
        double delval=cnfn.norm();
        objval+=delval*WxJ;

        //SETTING GRADIENT OF STRESS DOF

        Eigen::MatrixXd CxBs = m_material->get_cmat()*Bs;
        Eigen::MatrixXd Bstrans = CxBs.transpose();
        Eigen::RowVectorXd gradval= (-WxJ/delval)*Bstrans*cnfn;
        sdf_grad+= gradval ; // Wrong Result.

    }
}

Solution

  • You did not zero initialize your vector. Write this instead of the first line:

    Eigen::RowVectorXd sdf_grad = Eigen::RowVectorXd::Zero(24);