有没有更好的方法在MATLAB中声明一个空的类型化矩阵? [英] Is there a better way to declare an empty, typed matrix in MATLAB?

查看:313
本文介绍了有没有更好的方法在MATLAB中声明一个空的类型化矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MATLAB中是否可以用一种特定的用户定义类型来声明"变量? zeros()仅适用于内置数字类型.我想出的唯一解决方案涉及使用repmat()将虚拟对象复制零次:

Is there a way to "declare" a variable with a particular user-defined type in MATLAB? zeros() only works for built-in numeric types. The only solution I've come up with involves using repmat() to duplicate a dummy object zero times:

arr = repmat(myClass(), [1 0])

如果不以这种方式声明变量,则任何执行"arr(end + 1)= myClass()"的代码都必须为类型为double的默认空矩阵包括特殊情况.

Without declaring variables this way, any code which does "arr(end+1) = myClass()" has to include a special case for the default empty matrix which is of type double.

我错过了一些更明智的事情吗?

Have I missed something a little more sensible?

推荐答案

根据此文档,所有类都有一个empty方法,该方法创建该类的空数组.例如:

According to this documentation, all classes have an empty method that creates empty arrays of that class. For example:

arr = myClass.empty(0,0);  %# Creates a 0-by-0 array of class myClass

对于内置类型也是如此:

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


您提到过,您将通过以下方式循环增加此数组:

You mentioned that you will be growing this array in a loop in the following way:

arr(end+1) = myClass();

如果您知道阵列的最终大小,通常另一个问题的答案.

If you know what the final size of the array will be, it is generally more efficient to preallocate the entire array outside of the loop and then overwrite or modify the array elements in your loop. I discuss how you can do this for user-defined classes in an answer to another question.

这篇关于有没有更好的方法在MATLAB中声明一个空的类型化矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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