Sizeof double float int etc
조회 수: 100 (최근 30일)
이전 댓글 표시
Hello there,
I need to know how to find an equivallent function in Matlab to the sizeof function in c++.
For example, in c++ if I write sizeof(double) I would get the amount of memory needed to store a double.
I need something very similar with a matrix now. I will be storing bigger and bigger matrix and I need to find their size in the memory.
Could someone of you please help me?
all best,
:)
채택된 답변
Jan
2021년 6월 30일
편집: Jan
2021년 6월 30일
Version 1:
w = whos('z');
nbytes = w.bytes;
Version 2:
function S = sizeof(X)
switch class(X)
case {'uint64', 'int64', 'double'}
m = 8;
case {'uint32', 'int32', 'single'}
m = 4;
case {'uint16', 'int16', 'char'}
m = 2;
case {'uint8', 'int8', 'logical'}
m = 1;
otherwise
error('Jan:sizeof:Type', 'Type not handles: %s', class(X));
end
S = m * numel(X);
end
A search inthe forum leads me to: https://www.mathworks.com/matlabcentral/answers/391214-does-matlab-have-a-function-which-is-similar-with-sizeof-in-c#answer_312420 . Obviously I have some standard programming styles...
댓글 수: 0
추가 답변 (3개)
Steven Lord
2021년 6월 30일
I need something very similar with a matrix now. I will be storing bigger and bigger matrix and I need to find their size in the memory.
Why? If you're trying to create an array to be filled in, just call a function like ones or zeros and tell it the size of the array you want to create (in terms of number of elements) and optionally the type. There's no need for you to know (or care) how much memory each element takes up in order to build the array.
A = ones(2, 3, 'int16')
B = zeros(5) % 5-by-5 double array
댓글 수: 0
Fangjun Jiang
2021년 6월 30일
Look at the .bytes returned by whos()
a=false(5);
aInfo=whos('a')
b=zeros(5);
bInfo=whos('b')
댓글 수: 0
Kevin Holt
2024년 8월 16일
편집: Kevin Holt
2024년 8월 16일
Another option:
function n = sizeof(type)
dummy = zeros(1,type);
n = length(typecast(dummy,'int8'));
Then you can use it for various (non-complex) numeric types, e.g.
sizeof('double') returns 8
whos seems a little more general though.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!