Gregor Isack
Gregor Isack

Reputation: 1131

How can I determine the size of variable in memory WITHOUT creating it?

Is that possible? Let's say I wanted to determine how many bytes a variable WILL occupy given I know the dimension, so that an appropriate procedure can be taken before doing the computation. The classic way:

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

You might suggest to just delete the variable after the whos command, but if MATLAB has almost reached the max memory capacity, this might not work. Is there an elegant way to do this?

Upvotes: 3

Views: 2268

Answers (1)

gnovice
gnovice

Reputation: 125854

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 of type double by default, which is 8 bytes, so your total matrix size will be:

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

You can figure out 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 like cell arrays and structures make it a little bit more complicated to compute the total byte usage since they require some memory overhead.

Upvotes: 5

Related Questions