如何用1和0代替矩阵正值

如何用1和0代替矩阵正值

本文介绍了特征值:如何用1和0代替矩阵正值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Eigen中编写以下matlab代码(其中Kpxp,而Wpxb):

I want to write the following matlab code in Eigen (where K is pxp and W is pxb):

H = (K*W)>0;

但是到目前为止,我唯一想到的是:

However the only thing that I came up so far is:

H = ((K*W.array() > 0).select(1,0));

此代码无法按此处中的说明进行操作,而是将0替换为VectorXd::Constant(p,0)(如链接问题中所述)会生成运行时错误:

This code doesn't work as explained here, but replacing 0 with VectorXd::Constant(p,0) (as suggested in the link question) generates a runtime error:

Eigen::internal::variable_if_dynamic<T, Value>::variable_if_dynamic(T) [with T = long int; int Value = 1]: Assertion `v == T(Value)' failed.

我该如何解决?

推荐答案

您不需要.select().您只需要将bool的数组强制转换为H的组件类型的数组.

You don't need .select(). You just need to cast an array of bool to an array of H's component type.

H = ((K * W).array() > 0.0).cast<double>();


您的原始尝试失败,因为常量1/0数组的大小与H的大小不匹配.当HMatrixXd时,使用VectorXd::Constant不是一个好的选择.括号也有问题.我想您想要的是*而不是Matlab表示法的.*.


Your original attempt failed because the size of your constant 1/0 array is not match with the size of H. Using VectorXd::Constant is not a good choice when H is MatrixXd. You also have a problem with parentheses. I think you want * rather than .* in matlab notation.

#include <iostream>
#include <Eigen/Eigen>
using namespace Eigen;

int main() {
  const int p = 5;
  const int b = 10;
  MatrixXd H(p, b), K(p, p), W(p, b);
  K.setRandom();
  W.setRandom();
  H = ((K * W).array() > 0.0).cast<double>();
  std::cout << H << std::endl << std::endl;

  H = ((K * W).array() > 0).select(MatrixXd::Constant(p, b, 1),
                                   MatrixXd::Constant(p, b, 0));
  std::cout << H << std::endl;
  return 0;
}


在模板中调用模板成员函数时,需要使用template关键字.


When calling a template member function in a template, you need to use the template keyword.

#include <iostream>
#include <Eigen/Eigen>
using namespace Eigen;

template<typename Mat, typename Vec>
void createHashTable(const Mat &K, Eigen::MatrixXi &H, Mat &W, int b) {
  Mat CK = K;
  H = ((CK * W).array() > 0.0).template cast<int>();
}

int main() {
  const int p = 5;
  const int b = 10;
  Eigen::MatrixXi H(p, b);
  Eigen::MatrixXf W(p, b), K(p, p);
  K.setRandom();
  W.setRandom();
  createHashTable<Eigen::MatrixXf, Eigen::VectorXf>(K, H, W, b);
  std::cout << H << std::endl;
  return 0;
}

对此进行一些解释.

通过模板强制转换C ++ Eigen :: Matrix类型

这篇关于特征值:如何用1和0代替矩阵正值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 06:42