Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reshape a matrix?

Tags:

c++

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.

like image 320
cdeterman Avatar asked Nov 03 '14 17:11

cdeterman


People also ask

Why do we do reshape (- 1 1?

If you have an array of shape (2,4) then reshaping it with (-1, 1), then the array will get reshaped in such a way that the resulting array has only 1 column and this is only possible by having 8 rows, hence, (8,1).

How do you reshape a matrix size in Matlab?

B = reshape( A , sz ) reshapes A using the size vector, sz , to define size(B) . For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix. sz must contain at least 2 elements, and prod(sz) must be the same as numel(A) . B = reshape( A , sz1,...,szN ) reshapes A into a sz1 -by- ...


1 Answers

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.

like image 51
Marco A. Avatar answered Sep 29 '22 14:09

Marco A.