Suppose you had a 3 x 12 uint8 matrix, and wanted to typecast it to uint32: what would you want that to mean? What shape would you expect the result to be? There is the right amount of data there to make it in to 9 uint32 but 3 x 3 would surely be the wrong shape for the output, considering that the 4th byte of the first uint32 would have to be taken from the top row of the second column of the input array.
About the only way that would make sense to me to more or less preserve the dimensions would be if, when a type was being typecast to another type, the first dimension of the output would be adjusted so as the occupy the same number of bytes per column as the original first dimension did (getting bigger if the new type used less room, getting smaller if the new type occupied more room), with it being an error if the first column could not be converted to an integral number of items in the new type.
If that is the rule you would use, it would not be difficult to implement it. Keep in mind that reshape() and (:) do not move data around, just put a new header on it, so the operations would be fast:
function NewArray = typecastarray(TheArray, NewType)
curshape = num2cell(size(TheArray));
NewArray = reshape( typecast(TheArray(:),NewType), [], curshape{2:end});
end
2 Comments
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/16394-typecasting-higher-dimension-matrices#comment_36216
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/16394-typecasting-higher-dimension-matrices#comment_36216
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/16394-typecasting-higher-dimension-matrices#comment_36222
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/16394-typecasting-higher-dimension-matrices#comment_36222
Sign in to comment.