使用std::vector或数组初始化boost矩阵

8
我有一个方法,其中一个参数是std :: vector。是否有一种方法可以通过将std :: vector分配给矩阵来初始化矩阵?以下是我尝试的内容。有人知道如何将向量(甚至是双指针)分配给矩阵吗?先感谢大家。Mike
void Foo(std::vector v)
{
    matrix<double> m(m, n, v);
    // work with matrix...
}

1
矩阵是一个二维结构,向量是一个一维结构。您打算如何通过检查向量来确定矩阵的正确维度? - Mankarse
4个回答

6
这里有另一个示例,说明如何实现这一点:
#include <algorithm>
#include <vector>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

namespace ublas = boost::numeric::ublas;

template <typename T, typename F=ublas::row_major>
ublas::matrix<T, F> makeMatrix(std::size_t m, std::size_t n, const std::vector<T> & v)
{
    if(m*n!=v.size()) {
        ; // Handle this case
    }
    ublas::unbounded_array<T> storage(m*n);
    std::copy(v.begin(), v.end(), storage.begin());
    return ublas::matrix<T>(m, n, storage);
}

int main () {;
    std::vector<double> vec {1, 2, 3, 4, 5, 6};
    ublas::matrix<double> mm = makeMatrix(3,2,vec);
    std::cout << mm << std::endl;
}

4
根据增强矩阵文档,矩阵类有3个构造函数:空、复制和使用两个size_types参数来指定行数和列数。由于boost没有定义它(可能是因为有很多方法可以实现,并不是每个类都会定义到每个其他类的转换),您需要定义转换。

这是我会使用的方法,但由于有多种方法可以实现,而且问题没有具体说明如何实现,您可能会发现其他方法更适合您的情况。

void Foo(const std::vector<double> & v) {
   size_t m = ... // you need to specify
   size_t n = ... // you need to specify

   if(v.size() < m * n)   { // the vector size has to be bigger or equal than m * n
      // handle this situation
   }

   matrix<double> mat(m, n);
   for(size_t i=0; i<mat.size1(); i++) {
      for(size_t j=0; j<mat.size2(); j++) {
         mat(i,j) = v[i+j*mat.size1()];
      }
   }
}

关于您提供的代码,需要注意以下几点:std::vector需要一个模板参数,并且您将m声明为矩阵和其构造函数的输入参数。

4
更方便的方法是这样的:
matrix<double> m(m*n);
std::copy(v.begin(), v.end(), m.data().begin());

1
简单的答案,但从Boost文档中并不是很明显。您可以只使用std::vector<>作为存储数组模板参数的类型,而不是默认的unbounded_array<>来存储矩阵。 (在matrix<>类的文档注释2中提到了这一点。)
void Foo(const std::vector<double> &v, size_t n)
{
    using namespace boost::numeric::ublas;

    size_t m = v.size() / n;
    matrix< double, row_major, std::vector<double> > M(m, n);
    M.data() = v;

    // work with matrix...
}

更多初始化的变体可以在您的boost源代码中找到:boost/libs/numeric/ublas/doc/samples/assignment_examples.cpp,如此处所指出:在c++中将多个值分配给boost::numeric::ublas::vector 或者在这里:uBLAS示例,示例3,该示例由相关问题提到:ublas:将ublas :: vector包装为ublas :: matrix_expression

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接