How to determine the size of a variable in memory WITHOUT creating it?

Is it possible? Let's say I would like to determine how many bytes the WILL variable takes , given that I know the dimension, so that the appropriate procedure can be done before performing the calculation. The classic way:

A = zeros(500, 500, 500);
whos A;

      

You might suggest just deleting the variable after the command whos

, but if MATLAB has nearly reached its maximum memory capacity, this may not work. Is there an elegant way to do this?

+3


source to share


1 answer


For matrices of standard numeric types, all you need to know is the number of elements in your matrix and the number of bytes in the data type. For your example, your matrix will be double

of the default type , which is 8 bytes, so your total matrix size will be:

matrixSize = [500 500 500];
byteSize = prod(matrixSize)*8;

      

You can determine the byte size for a given data type from a scalar variable of that type using whos

:



temp = uint8(0);           % Sample uint8 variable
varData = whos('temp');    % Get variable data from whos
varBytes = varData.bytes;  % Get number of bytes

varBytes =

     1                     % uint8 takes 1 byte

      

As mentioned by Sam , container classes such as cell arrays and structures make it a little more difficult to compute the total byte usage as they require some memory overhead.

+5


source







All Articles