Eigen equivalent of Matlab rescale command

三世轮回 提交于 2019-12-24 07:16:35

问题


I'd like to recreate the Matlab rescale command in Eigen

https://www.mathworks.com/help/matlab/ref/rescale.html

I've tried to translate but not sure about it. My Eigen knowledge is too limited still...

  auto rescale = [&](
    Eigen::MatrixXd mat, 
    Eigen::VectorXd inmin,
    Eigen::VectorXd inmax,
    Eigen::VectorXd l,
    Eigen::VectorXd u
    ) -> Eigen::MatrixXd {

    auto val = l.array() + (
      ((mat - inmin).array()) / ((
        ((inmax - inmin).array()) * ((u - l).array())
      ).array())
    );

    return val;
  };

could this be viable?


回答1:


No. Your dimensions don't match. You're mixing ArrayXd and ArrayXXd. This is more like what you want, with a version for scalars and another for vectors. Adjust the rowwise/colwise to match the different versions of matlabs rescale.

#include <Eigen/Core>
#include <iostream>

int main()
{

    auto rescale = [&](
        Eigen::MatrixXd mat,
        double l,
        double u
        ) -> Eigen::MatrixXd {

        double min = mat.minCoeff();
        double max = mat.maxCoeff();
        auto val = l + (mat.array() - min) * ((u - l) / (max - min));
        return val;
    };

    Eigen::MatrixXd mat(4,4);
    Eigen::Map<Eigen::VectorXd>(mat.data(), mat.size()).setLinSpaced(1, mat.size());

    std::cout << mat << "\n\n";

    auto rescaled = rescale(mat, 2, 5);

    std::cout << rescaled << "\n\n";

    auto rescale2 = [&](
        Eigen::MatrixXd mat,
        Eigen::VectorXd l,
        Eigen::VectorXd u
        ) -> Eigen::MatrixXd {

        Eigen::ArrayXd  min = mat.colwise().minCoeff();
        Eigen::ArrayXd  max = mat.colwise().maxCoeff();
        auto val = l.array().replicate(1, mat.cols())
            + ((mat.array().rowwise() - min.transpose()).rowwise() * 
               ((u - l).array() / (max - min)).transpose());
        return val;
    };

    Eigen::VectorXd mn, mx;

    mn.resize(mat.cols());
    mx.resize(mat.cols());

    mn.setConstant(1.3);
    mx << 2, 5, 6, 9;
    rescaled = rescale2(mat, mn, mx);

    std::cout << rescaled << "\n\n";



    return 0;
}


来源:https://stackoverflow.com/questions/56116182/eigen-equivalent-of-matlab-rescale-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!