如何初始化类句柄的向量? [英] How to initialize a vector of class handles?

查看:107
本文介绍了如何初始化类句柄的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于句柄的类,需要为其创建向量.一种简单的方法是在for循环中动态构造矢量,但这会导致 mlint 抱怨矢量大小的变化.

I have a handle-based class that I need to create a vector of. An easy method of doing this is to dynamically construct the vector in a for loop, but this causes mlint to complain about the changing vector size.

classdef HandleClass < handle
    ...
end

...

for i = 1:10
    foo(i) = HandleClass();
end

我怀疑使用此方法分配大量复杂对象所需的资源.

I'm suspicious of the resource-hit required to use this method to allocate large arrays of complicated objects.

上一个线程中的评论描述了一个有用的 repmat 函数创建矢量的方法.但是,@ gnovice警告说,这样做会创建指向同一对象的句柄向量.我已经测试过了,看来确实是这样.

A comment in a previous thread described a useful method to create a vector using the repmat function. However, @gnovice warned that doing that would create a vector of handles pointing to the same object. I have tested this and it appears to be the case.

是否有一个窍门,可以在不使用 for 循环的情况下预先分配唯一的手柄对象向量?

Is there a trick that allows a vector of unique handle objects to be pre-allocated without the use of a for loop?


解决方案摘要

解决方案 SCFrench 正确分配了用于创建对象向量的内存.其他解决方案将创建矢量,但不会分配内存.

The solution presented by SCFrench correctly allocates the memory for the creation of a vector of objects. Other solutions will create the vector, but will not allocate the memory.

foo(10) = HandleClass();

推荐答案

foo(10) = HandleClass();

这将默认填充foo(1)到foo(9).

This will default fill foo(1) through foo(9).

请注意,这仅在HandleClass的构造函数没有输入参数的情况下才有效(也就是说,它可以是默认构造的).

Note that this only works if HandleClass's constructor works with no input arguments (that is, it can be default-constructed).

这篇关于如何初始化类句柄的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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