필터 지우기
필터 지우기

Determine number of bytes per element under program control

조회 수: 23 (최근 30일)
Daniel Lyddy
Daniel Lyddy 2014년 7월 2일
댓글: Oliver Woodford 2015년 11월 13일
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.

답변 (2개)

dpb
dpb 2014년 7월 3일
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...
  댓글 수: 3
dpb
dpb 2014년 7월 4일
I tend to forget about the command form for whos ... good thought; simpler than the isa route, indeed.
Oliver Woodford
Oliver Woodford 2015년 11월 13일
Uint8 means 8 bits, so only 1 byte. A switch on class(x) is another option.

댓글을 달려면 로그인하십시오.


James Tursa
James Tursa 2014년 7월 3일
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'))
  댓글 수: 2
dpb
dpb 2014년 7월 4일
Wrap the mex-call in a mex-routine???
James Tursa
James Tursa 2014년 7월 5일
As requested:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if( nrhs ) {
plhs[0] = mxCreateDoubleScalar(mxGetElementSize(prhs[0]));
}
}

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Database Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by