gpt4 book ai didi

matlab - 如何知道 MATLAB 中变量的大小

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:14 24 4
gpt4 key购买 nike

我在 MATLAB 中有变量,我已经使用 class() 检查了它们的类,但我也想知道它们在内存中占用的大小。更准确地说,我知道它们是 double 类型,我想确保它们是 32 位 double 而不是 64 位。

我使用的 MATLAB 版本是 R2009b。

最佳答案

我编写了一个简单的便捷函数来处理这个问题。用法是:

>> x = ones(1000);
>> ByteSize(x)
7.63 Mb

我运行的是 R2007a,因此 Java 对象不返回大小的问题可能已在后续版本中得到修复。这是代码:

function ByteSize(in, fid)
% BYTESIZE writes the memory usage of the provide variable to the given file
% identifier. Output is written to screen if fid is 1, empty or not provided.

if nargin == 1 || isempty(fid)
fid = 1;
end

s = whos('in');
fprintf(fid,[Bytes2str(s.bytes) '\n']);
end

function str = Bytes2str(NumBytes)
% BYTES2STR Private function to take integer bytes and convert it to
% scale-appropriate size.

scale = floor(log(NumBytes)/log(1024));
switch scale
case 0
str = [sprintf('%.0f',NumBytes) ' b'];
case 1
str = [sprintf('%.2f',NumBytes/(1024)) ' kb'];
case 2
str = [sprintf('%.2f',NumBytes/(1024^2)) ' Mb'];
case 3
str = [sprintf('%.2f',NumBytes/(1024^3)) ' Gb'];
case 4
str = [sprintf('%.2f',NumBytes/(1024^4)) ' Tb'];
case -inf
% Size occasionally returned as zero (eg some Java objects).
str = 'Not Available';
otherwise
str = 'Over a petabyte!!!';
end
end

关于matlab - 如何知道 MATLAB 中变量的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4845561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com