将选择的行复制到新矩阵中 [英] Copy select rows into new matrix

查看:81
本文介绍了将选择的行复制到新矩阵中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以此顺序将矩阵A的行0、2和4复制到B中. 令A = [a0,a1,a2,a3,a4] ^ T,其中a_i是行向量, 那么B应该是:[a0,a2,a4] ^ T.

I want to copy the rows 0, 2 and 4 of my matrix A into B, in this order. Let A = [a0, a1, a2, a3, a4]^T , with a_i being row-vectors, then B should be: [a0, a2, a4]^T.

下面的代码是我想要的,但是我想知道是否有一个更漂亮的解决方案(也许使用Eigen)?

The code below does what I want but I wonder whether there is a prettier solution (maybe using Eigen)?

#include <iostream>
#include <vector>
#include <opencv/cv.h>


int main(int argc, char **argv) {
    const int num_points = 5;
    const int vec_length = 3;
    cv::Mat A(num_points, vec_length, CV_32FC1);
    cv::RNG rng(0); // Fill A with random values
    rng.fill(A, cv::RNG::UNIFORM, 0, 1);
// HACK Ugly way to fill that matrix .
    cv::Mat B = cv::Mat(3,vec_length, CV_32FC1);
    cv::Mat tmp0 = B(cv::Rect(0,0,vec_length,1));
    cv::Mat tmp1 = B(cv::Rect(0,1,vec_length,1));
    cv::Mat tmp2 = B(cv::Rect(0,2,vec_length,1));
    A.row(0).copyTo(tmp0);
    A.row(2).copyTo(tmp1);
    A.row(4).copyTo(tmp2);

    std::cout << "A: " << A << std::endl;
    std::cout << "B: " << B << std::endl;
    return 0;
}

推荐答案

我找到了push_back.

使用size 0 x vec_length创建B,然后使用push_backA添加选定的行:

Create B with size 0 x vec_length and then use push_back to add the selected rows from A:

#include <iostream>
#include <vector>
#include <opencv/cv.h>


int main(int argc, char **argv) {
    const int num_points = 5;
    const int vec_length = 3;
    cv::Mat A(num_points, vec_length, CV_32FC1);
    cv::RNG rng(0); // Fill A with random values
    rng.fill(A, cv::RNG::UNIFORM, 0, 1);
    cv::Mat B = cv::Mat(0,vec_length, CV_32FC1);
    B.push_back(A.row(0));
    B.push_back(A.row(2));
    B.push_back(A.row(4));
    std::cout << "A: " << A << std::endl;
    std::cout << "B: " << B << std::endl;
    return 0;
}

这篇关于将选择的行复制到新矩阵中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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