Matlab使用什么算法来动态调整向量和矩阵的大小? [英] What algorithm does Matlab use to dynamically resize vectors and matrices?

查看:366
本文介绍了Matlab使用什么算法来动态调整向量和矩阵的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码:

n = 5;
x = zeros(n, 1);
for ix=1:10
   x(ix) = rand();
   disp(getfield(whos('x'), 'bytes'))
end

输出以下内容:

40
40
40
40
40
48
56
64
72
80

似乎表明,当Matlab调整向量的大小时,它会调整其大小以使其具有恰好需要的空间,不再有更多空间.因此,一次只需要一个元素.

which seems to indicate that when Matlab resizes a vector, it resizes it to have exactly as much space as it needs, no more. So, one element at a time.

将此与Sun的ArrayList的Java实现中的方法进行对比,该方法分配了足够的空间,因此不会每次调整大小超出初始界限的每次分配都需要发生.显然,由于Matlab不是开源的,所以没有办法告诉100%他们做什么,但是有没有更好的办法来了解调整大小的方式呢?上面的代码不是估算此代码的好方法吗?

Contrast this with the method in Sun's Java implementation of ArrayList, which allocates enough space so that every resizing won't need to happen on every assignment above the initial bound. Obviously since Matlab isn't open source there's no way to tell 100% what they do, but is there a better way to get some idea of how the resizing is done? Is the code above not a good way to estimate this?

推荐答案

来自

From MathWorks' software development manager Steve Eddins:

MATLAB使用更智能的启发式方法,而不是在需要更多空间时简单地将分配的内存空间加倍,因此,对于大型阵列,最坏情况下的内存过度分配"要小于两倍.我不打算在这里进一步讨论细节,因为(a)我不了解它们,并且(b)我希望我们将在未来的发行版中继续调整自动阵列增长的启发式方法和其他方面.

MATLAB uses a smarter heuristic than simply doubling the allocated memory space whenever more is needed, so for large arrays the worst-case memory "overallocation" is much less than a factor of two. I don't intend to get into further details here because (a) I don't know them, and (b) I expect that we will continue to tune the heuristic and other aspects of automatic array growth with future releases.

因此,可以肯定地说,它不会一次为一个元素分配空间,而是在一定程度上进行了分配.此外,正如亚历山大·比索(Alexandre Bizeau)所指出的,记忆将是连续的.

So, it is safe to say it does not allocate space for one element at a time, but overallocates to some degree. Also, as noted by Alexandre Bizeau, the memory will be contiguous.

另外,请参阅此页面以了解阵列增长的性能分析.

Also, see this page for an array grown performance analysis.

这篇关于Matlab使用什么算法来动态调整向量和矩阵的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆