Reputation: 21986
reshape function should change the shape of a matrix. But if I try using it (it's also written in the manual) I discover that if I declare: reshape(A,m,n); Then A must have m lines and n columns. If I try using reshape passing as arguments numbers different from these, I get an error. So appearently, it does not reshape any matrix, it just does return the same matrix if I pass m and n as arguments, and return an error otherwise. So if I have a 4x4 matrix and I want to make it smaller: 2x2, I can't.
Upvotes: 0
Views: 1008
Reputation: 26612
Reshape rearranges elements; if you do B = reshape(A, u)
then logically B must have the same number of elements (note that size(B) == prod(u)
) as A (length(B(:)) == length(A(:))
). Otherwise, how would it know which elements to drop if A had more, or where would it get new ones if B had more?
One situation in which reshape is useful is when for some reason your square matrix was unrolled into a vector (perhaps by another function) and you simply need to arrange it back to its previous form.
When you want to get a smaller part of a matrix, use A(i1:i2, j1:j2)
. When you want to "tile" a matrix, use repmat(A, i, j)
.
Upvotes: 4
Reputation: 8864
As @thrope says, reshape
changes the shape, not the number of elements. If you have a 4x4 matrix and you want the upper left 2x2 corner of it, use B=A(1:2,1:2)
or the bottom right 2x2 corner, B=A(3:4,3:4)
.
Upvotes: 2
Reputation: 10967
It changes the shape, not the size of the array. To change the shape the number of elements must not change. So if you have 4x4 you can go to 8x2 or 2x8 or 16x1 etc. but not 2x2 (what do you expect to happen to the other elements?)
Upvotes: 6