c++matrix

How to reshape a matrix?


I am currently trying to convert some Python code into C++. One 'small' problem is changing the dimensions of a matrix. Is it possible to reshape a matrix in C++ similar to the Python reshape function?

For example, in Python I can easily create an array with numpy and easily reshape the dimensions.

a = np.array([[1,2,3],[4,5,6]])
>>> a.reshape(3,2)
array([[1, 2],
       [3, 4],
       [5, 6]])

How could I do this in C++? Perhaps this is a simple question but I am completely unable to do this. I have seen this within OpenCV library with the Mat class here however it is proving to be insanely difficult to work properly with MinGW, not to mention a very large addition for a single function. It would be ideal if this was possible with 'base' functions.


Solution

  • As far as the memory is laid contiguously (e.g. plain C arrays), you can reinterpret the type with different indices:

    int array[2][3] =   {   { 1, 2, 3 },
                            { 4, 5, 6 } 
                        };
    
    // Reinterpret the array with different indices
    int(*array_pointer)[3][2] = reinterpret_cast<int(*)[3][2]>(array);
    
    for (int x = 0; x < 3; ++x) {
        for (int y = 0; y < 2; ++y)
            std::cout << (*array_pointer)[x][y] << " ";
        std::cout << std::endl;
    }
    // Output:
    // 1 2
    // 3 4
    // 5 6
    

    Example

    The above is just an example to show that the issue really boils down to how memory is laid out in your matrix class.

    In case your class uses a std::vector<int> internally with linear indices, it is sufficient to reinterpret those indices to suit your access patterns.