MATLAB 中的动态内存分配

Dynamic memory allocation in MATLAB

我有两个问题:

  1. 什么是 MATLAB 等同于 Crealloc()? 那是reshape()吗?
  2. 如何初始化可用于增量添加 object/struct 类型的新元素的 MALTAB 向量?

比如my_vector = zeros(1, N)不能用在objects/structs的情况下,对吧?

在 MATLAB 中,内存分配是自动完成的。即,向向量添加元素会自动执行 realloc

x = [ 1 2 3 ];
x(4) = 4;  % performs realloc
% now x == [1 2 3 4]

x(2) = []; % deletes element 2
% now x == [1 3 4]

为了创建对象数组,我过去使用 repmat。由于一般情况下的对象需要从一些数据构造,我发现如果对 class 没有其他了解,复制通常是最好的。要创建 class CLS 的默认构造对象的 2x3x4 数组,请使用

x = repmat( CLS(), [ 2 3 4] )

我发现这比写

更合适
x = CLS();
x(2,3,4) = CLS();

这可能也可以工作,但阅读起来很笨拙,如果 class 没有正确实施,可能会有细微的错误。

structs 也可以使用 repmat 创建,或者,也可以通过向 struct 构造函数提供元胞数组来创建,例如,

x = struct( 'a', { 1 2 3}, 'b', { 5 6 7} );
% now x is a 1x3 struct array