Search code examples
matlabmatrixtypecast-operator

Why typecasting increases matrix's row/column size?


when I write this code (just for testing. This thing occurs other type casting too):

y_quan=typecast(y_quan,'int8');

dimension of y_quan changes drastically . Before typecasting it was a double type 1X15310 matrix. But after this typecasting operation it became int8 type 1X122480 matrix. why this is happening ? anyone please explain. How can I prevent this?


Solution

  • How can I prevent this?

    Don't use typecast, it's obviously the wrong function.

    That's the behaviour you're explicitely asking for. From the Matlab documentation, which is the obvious place that someone should look when researching functionality:

    typecast is different from the MATLAB® cast function in that it does not alter the input data. typecast always returns the same number of bytes in the output Y as were in the input X. For example, casting the 16-bit integer 1000 to uint8 with typecast returns the full 16 bits in two 8-bit segments (3 and 232) thus keeping its original value (3*256 + 232 = 1000). The cast function, on the other hand, truncates the input value to 255.

    Which means that your double matrix, which has 64 bit per element, has 15310 * 8 Byte storage. Now, typecasting that to 8-bit (==1Byte) values, ithe result has 8 times as many elements.