From the documentation
The data type and number of elements in B are the same as the data type and number of elements in A. The elements in B preserve their column-wise ordering from A.
If you need the result to be the same size as the original, just store the size before the initial transformation and use this as the input to reshape
after performing your manipulation of the data.
% Store the original size
originalSize = size(data);
% Reshape it to your new 2D array
data = reshape(data, [], 3);
% Do stuff
% Reshape it back to it's original size
data = reshape(data, originalSize);
In the 2D version, the elements won't technically be in the same position as they were in the 3D matrix because...well..it's 2D not 3D. But, if you reshape it back to the 3D (without moving elements around), the element ordering would be the same as the original 3D matrix.
Update
You can easily check this for yourself.
R = rand([10, 20, 3]);
isequal(R, reshape(reshape(R, [], 3), size(R)))
The reason for why this is is because reshape
does not actually change the underlying data but rather the way in which it is accessed. We can easily check this by using format debug
to see where the data is stored.
We can also use a little anonymous function I wrote to see where in memory a given variable is stored.
format debug;
memoryLocation = @(x)regexp(evalc('disp(x)'), '(?<=pr\s*=\s*)[a-z0-9]*', 'match')
Ok so let's create a matrix and check where MATLAB stored it in memory
A = rand(10);
memoryLocation(A)
% 7fa58f2ed9c0
Now let's reshape it and check the memory location again to see if it is in a different place (i.e. the order or values were modified)
B = reshape(A, [], 10);
memoryLocation(B)
% 7fa58f2ed9c0
As you can see, the memory location hasn't changed meaning that the ordering of elements has to be the same otherwise MATLAB would have needed to make a copy in memory.