【问题标题】:structure field is function matlab结构域是函数matlab
【发布时间】:2013-08-07 18:05:40
【问题描述】:

我问这个问题是为了测试一个概念。我不想在代码中提供解决方案,我只需要关于继续前进的方向的建议。

我想创建一个结构字段,它始终是相同结构的其他字段的函数。

我已经能够实现可以修改现有结构并使用新字段对其进行更新的代码。但是,如果不重新初始化代码,这是行不通的,这并不理想。

我需要能够添加另一个结构,为某些字段赋予值,然后通过我定义的函数自动更新其余字段。

结构是完成这项任务的正确方法吗?我认为不是,但我不确定可以使用什么方法。

我附上了一个非常简单的代码 sn-p 来演示这个问题。

    module = struct('dim', [ 3 1 0.05], ...
                    'point', [0 0 0],   ...
                     'shape', cubeshape(module.dim,module.point))
                              % cubeshape is my function of dim & point

matlab 返回错误....

    Undefined function or variable 'dim'.

这是有道理的,因为 struct() 函数尚未关闭 这意味着模块结构尚未定义。

如果我的问题太新手,请告诉我我可以继续研究,但不胜感激。

谢谢!

【问题讨论】:

    标签: matlab object structure


    【解决方案1】:

    您可以将'shape' 字段设置为function handle

    module = struct('dim', [3 1 0.05], ...
                    'point', [0 0 0], ...
                    'shape', @()cubeshape(module.dim,module.point))
    

    然后通过

    访问'shape'字段的值
    module.shape()
    

    但是,您会发现,如果您在结构中更改 module.dim 的值,module.shape() 返回的值不会更新。这是因为两个函数句柄参数是在实例化时设置的。你可能不想要这个。相反,您可以将 module.dimmodule.point 作为参数传递到函数句柄中:

    module = struct('dim', [3 1 0.05], ...
                    'point', [0 0 0], ...
                    'shape', @(dim,point)cubeshape(dim,point))
    module.shape(module.dim,module.point)
    

    它不太优雅,但解决了问题,因为将使用 module.dimmodule.point 的当前值。

    还有许多其他方法可以解决您的问题。最标准的是通过object-oriented approaches。然而,有时,这就像用大锤敲打苍蝇(在 Matlab 的情况下为a very slow sledgehammer sometimes)。您也许可以通过函数做您需要的事情,并重新思考您的问题。

    【讨论】:

    • 感谢您的好评。假设我要向结构中添加 3 个模块,它们都可能具有不同的 dim 和 point 值。我每次都必须调用 module.shape(module.dim,module.point) 吗?
    • 我不知道您所说的“向结构中添加 3 个模块”是什么意思。您的结构本身称为module。你的意思是一个结构数组,即module(1) = struct(...)module(2) = struct(...),...?还是您的意思是添加更多字段? This video 可能会对您有所帮助。
    • 对不起,我的术语不够用。我想在结构数组中制作更多的模块结构。即module(1) = struct(...)module(2) = struct(...),我想让这些结构中的每一个的shape字段对应于dimpoint
    • 对于结构数组,您必须调用module(i).shape(module(i).dim,module(i).point); 但是如果您对结构数组的每个元素使用相同的函数cubeshape,那么即使在结构中使用它也可能没有意义.也许结构应该包含函数的结果,但要做到这一点,您需要跟踪每次修改任何字段的时间(这可以通过面向对象编程轻松完成)。
    猜你喜欢
    • 2017-04-22
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多