【问题标题】:Compare matrices multiplication比较矩阵乘法
【发布时间】:2010-06-25 16:26:02
【问题描述】:

我必须将一个矩阵自身相乘,直到该矩阵在某种程度上不等于前面的矩阵之一。然后我需要得到矩阵相等的度数。行数和列数相等。矩阵存储在二维数组中。值为 0 或 1。检查与先前矩阵是否相等的最佳方法是什么?我尝试使用vector 来存储矩阵:

vector<int[5][5]> m;

但我收到了错误cannot convert from 'const int [5][5]' to 'int [5][5]'

等待建议。

【问题讨论】:

  • 您可能应该发布导致编译错误的代码片段。
  • “在某种程度上”是指轮换吗? (或者我只是忘记了这个术语?)这些总是 5x5 方阵吗?
  • 我正在使用“vector m;”并得到错误。也许还有另一种存储矩阵的方法?矩阵可以是 3x3 或 4x4...这并不重要。
  • vector 是编译器错误的原因 - 你不能这样做。创建一个小型矩阵类来存储您的数据数组,然后在向量中使用它。
  • 当然 - 我真的在问它们是否是方阵,以尝试理解您的度数,但后来我发现错误消息中有 5x5。

标签: c++ arrays matrix


【解决方案1】:

如果可以使用boost,看一下boostMatrix类:

好像少了一个== 操作符,但是很容易添加:

#include <iostream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

using namespace boost::numeric::ublas;

template<typename T>
bool operator==(const matrix<T>& m, const matrix<T>& n)
{
  bool returnValue = 
    (m.size1() == n.size1()) &&
    (m.size2() == n.size2());

  if (returnValue)
  {
    for (unsigned int i = 0; returnValue && i < m.size1(); ++i)
    {
      for (unsigned int j = 0; returnValue && j < m.size2(); ++j)
      {
        returnValue &= m(i,j) == n(i,j);
      }
    }
  }
  return returnValue;
}

并像这样使用:

int main ()
{

  matrix<double> m (3, 3);
  for (unsigned int i = 0; i < m.size1(); ++ i)
  {
    for (unsigned int j = 0; j < m.size2(); ++ j)
    {
      m (i, j) = 3 * i + j;
    }
  }
  std::cout << m << std::endl;

  matrix<double> n (3, 3);

  std::cout << (m == n) << std::endl;
  std::cout << (m == m) << std::endl;
}

[Code]

【讨论】:

  • operator== 丢失,因为浮点(库的目标)的相等比较几乎没有意义。无论如何,有一个ublas::detail::equals(弱相等)使用起来更安全,因为它允许阈值。例如ublas::detail::equals(m1, m2, 1.e-6, 0.)。或者如果有人坚持template&lt;class M1, class M2&gt; bool operator==(M1 const&amp; m1, M2 const&amp; m2){return detail::equals(m1, m2, std::numeric_limits&lt;M1::value_type&gt;::epsilon(), std::numeric_limits&lt;M1::value_type&gt;::min());}(另外,如果尺寸不兼容,可能会或可能不是所需的行为,则抛出)
  • 在新的 gcc 用语(版本 > 5 和/或 C++11)中,typename 关键字是必需的,上面的函数应该是:template&lt;class M1, class M2&gt; bool operator==(M1 const&amp; m1, M2 const&amp; m2) { return detail::equals(m1,m2, std::numeric_limits&lt;typename M1::value_type&gt;::epsilon(),std::numeric_limits&lt;typename M1::value_type&gt;::min()); } You will note the typename` 关键字使用 numeric_limits 时.
【解决方案2】:

如果你想用vector 来做这件事,你可能需要vector &lt; vector &lt; int &gt; &gt;,即整数向量的向量(即一种二维向量)。

vector&lt;int[5][5]&gt; 将(如果有效)声明一个二维 5x5-int-arrays 向量。

【讨论】:

    猜你喜欢
    • 2016-07-31
    • 2014-07-14
    • 1970-01-01
    • 2018-11-29
    • 2012-07-14
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多