# Determine number of bytes per element under program control

134 views (last 30 days)
Daniel Lyddy on 2 Jul 2014
Commented: Oliver Woodford on 13 Nov 2015
Does MATLAB have the equivalent of the C/C++ 'sizeof' function?
I have some code that can run on many numeric types, and I need to be able to calculate the number of bytes per element in a given numeric array, let's call it 'A'
bytesPerElement = sizeof(class(A));
I suppose I could do something like:
w = whos(A);
bytesPerElement = w.bytes / numel(A);
but I would be surprised if there was not a function that calculates the number of bytes per element directly from the variable class. I just can't seem to find that function ... entering the wrong words into the search engine, I suppose.

dpb on 3 Jul 2014
No sizeof directly that I know of, no. Wouldn't be hard to build one from isa, however.
An outline would be something otoo--
function bytes = sizeof(x)
% return size in bytes of numeric entity x
bytes = (isa(x,'double') | isa(x,'int8') | isa(x,'uint8'))*8 + ...
(isa(x,'single') | isa(x,'int4') | isa(x,'uint4'))*4 + ...
...
The rest should be obvious... :)
doc isa % for the various class choices
Some checking for invalid types would be good, of course...

Daniel Lyddy on 3 Jul 2014
I ended up going the 'whos' route:
function bytes = bytesPerElement(x)
w = whos('x');
bytes = w.bytes / numel(x);
end
Simple enough, I guess, but I'm still perplexed that something like this doesn't exist already. I figured that such a function would have been used to calculate the 'bytes' field of the struct returned by whos, but since that function is mex-ified, I can't see what it's doing under the hood.
dpb on 4 Jul 2014
I tend to forget about the command form for whos ... good thought; simpler than the isa route, indeed.
Oliver Woodford on 13 Nov 2015
Uint8 means 8 bits, so only 1 byte. A switch on class(x) is another option.

James Tursa on 3 Jul 2014
There is a mex function for this, mxGetElementSize, but it doesn't do you much good at the m-file level:
Another way to do this assuming x is not empty (probably not any faster):
numel(typecast(x(1),'uint8'))

dpb on 4 Jul 2014
Wrap the mex-call in a mex-routine???
James Tursa on 5 Jul 2014
As requested:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if( nrhs ) {
plhs[0] = mxCreateDoubleScalar(mxGetElementSize(prhs[0]));
}
}