有没有办法在 MATLAB 中“声明”具有特定用户定义类型的变量? zeros() 仅适用于内置数字类型。我想出的唯一解决方案涉及使用 repmat() 零次复制虚拟对象:
arr = repmat(myClass(), [1 0])
如果不以这种方式声明变量,任何执行“arr(end+1) = myClass()”的代码都必须包含默认空矩阵的特殊情况,即 double 类型。
我是不是漏掉了一些更明智的东西?
最佳答案
根据 this documentation , 所有类都有一个 empty
方法来创建该类的空数组。例如:
arr = myClass.empty(0,0); %# Creates a 0-by-0 array of class myClass
对于 built-in types 也是如此:
a = uint8.empty(0,1); %# A 0-by-1 uint8 array
b = single.empty(5,0); %# A 5-by-0 single array
c = cell.empty(0,0); %# A 0-by-0 cell array
关于预分配的说明...
您提到您将通过以下方式循环增长此数组:
arr(end+1) = myClass();
如果您知道数组的最终大小,通常 preallocate the entire array 会更有效在循环之外,然后覆盖或修改循环中的数组元素。我在 an answer to another question 中讨论了如何为用户定义的类执行此操作.
关于matlab - 有没有更好的方法在 MATLAB 中声明一个空的类型化矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2594353/