使用特征库将列追加到矩阵 [英] Append column to matrix, using Eigen library

查看:86
本文介绍了使用特征库将列追加到矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的任务,但是我找不到它的答案:

It's quite a simple task, but I was not able to find an answer to it:

使用Eigen库,假设我有 Matrix2Xd垫 Vector2d vec ,其中

Using the Eigen library, suppose I have Matrix2Xd mat and Vector2d vec, where

mat = 1 1 1
      1 1 1
vec = 2 2

现在我需要类似 mat.addCol(vec)的东西,这样之后

Now I need something like mat.addCol(vec) such that afterwards

mat = 1 1 1 2
      1 1 1 2

什么是最好的(最简单的) )的方式来完成此操作?

What is the best (simplest) way to accomplish this?

请注意,这不是如何用本征矢量中的矩阵制作矩阵?。我不想一开始就构造矩阵,而是附加到现有矩阵上。还是有一个窍门,在这种情况下如何使用逗号初始化?以下代码将失败:

Please note, that this is not a duplicate of How do you make a matrix out of vectors in eigen?. I don't want to initialy construct the matrix but append to an existing one. Or is there maybe a trick, how to use the comma initialization in this case? The following code will fail:

Matrix2Xd mat(2,3);
Vector2d vec;
mat << 1, 1, 1, 1, 1, 1;
vec << 2, 2;

cout << mat << endl;
mat << vec;             // <-- crashes here
cout << mat << endl;






编辑:以下工作,但我不喜欢这样的基本任务需要临时变量。有更好的方法吗?


The following works, but I don't like the need of a temporary variable for such a basic task. Is there a better way?

Matrix2Xd tmp(2, mat.cols()+1);
tmp << mat, vec;
mat = tmp;


推荐答案

您可以使用 conservativeResize 为此:

mat.conservativeResize(mat.rows(), mat.cols()+1);
mat.col(mat.cols()-1) = vec;

这篇关于使用特征库将列追加到矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆