21xrx.com
2024-06-03 05:32:45 Monday
登录
文章检索 我的文章 写文章
C++与Matlab中的数组重塑操作(reshape)
2023-07-02 05:15:29 深夜i     --     --
C++ Matlab 数组 重塑操作 reshape

C++和Matlab都是常用的编程语言,它们都支持数组重塑操作(reshape)。

在C++中,可以使用std::reshape函数来进行重塑操作,它需要指定重塑后的行数和列数。比如,如果我们有一个10x10的矩阵,我们可以通过如下方式将其重塑为5x20的矩阵:


#include <iostream>

#include <vector>

void reshape(std::vector<int>& matrix, int rows, int cols)

{

  if(matrix.size() != rows * cols)

  

    std::cout << "Reshape failed: new matrix size does not match!" << std::endl;

    return;

  

  std::vector<int> newMatrix(rows * cols);

  for(int i = 0; i < rows * cols; i++)

  {

    int r = i / cols;

    int c = i % cols;

    int index = r * cols + c;

    newMatrix[index] = matrix[i];

  }

  matrix = newMatrix;

}

int main()

{

  std::vector<int> matrix =

    11;

  reshape(matrix, 5, 20);  //重塑为5x20的矩阵

  for(int i = 0; i < matrix.size(); i++)

  {

    std::cout << matrix[i] << " ";

    if((i + 1) % 20 == 0)

      std::cout << std::endl;

  }

  return 0;

}

在Matlab中,可以使用reshape函数来进行重塑操作,同样也需要指定重塑后的行数和列数。比如,我们可以将一个10x10的矩阵重塑为5x20的矩阵:

matlab

matrix = [1 2 3 4 5 6 7 8 9 10;

     11 12 13 14 15 16 17 18 19 20;

     21 22 23 24 25 26 27 28 29 30;

     31 32 33 34 35 36 37 38 39 40;

     41 42 43 44 45 46 47 48 49 50;

     51 52 53 54 55 56 57 58 59 60;

     61 62 63 64 65 66 67 68 69 70;

     71 72 73 74 75 76 77 78 79 80;

     81 82 83 84 85 86 87 88 89 90;

     91 92 93 94 95 96 97 98 99 100];

newMatrix = reshape(matrix, 5, 20);   %重塑为5x20的矩阵

disp(newMatrix);

可以看到,无论是C++还是Matlab,都可以很方便地进行数组重塑操作。这一操作在数据处理中十分常见,可以帮助我们更方便地对数据进行分析和处理。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章