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.
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).
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- ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With