【问题标题】:How can I vectorize access to substructures in Matlab?如何矢量化对 Matlab 中子结构的访问?
【发布时间】:2017-07-04 19:57:47
【问题描述】:

我会先跳到问题,然后是一些支持信息:

假设我有以下内容:

motor(1).Voltage = 96.2;
motor(2).Voltage = 48.0;

processingStation(1).FeedstockMotor.Voltage = 96.2;
processingStation(2).FeedstockMotor.Voltage = 48.0;

以下给出所有电机电压:

[motor.Voltage]

这并没有给出所有电机电压:

[processingStation.FeedstockMotor.Voltage]

第一个输出,[motor.Voltage],给了我结构中所有电机的电压。在另一种情况下,我如何获得相同的功能,我试图在所有processingStations 中比较FeedstockMotorVoltage 值?

我意识到我可以重命名字段 FeedstockMotor_Voltage 并获得相同的功能,但如果排放电机具有类似的配置集,那么我可以轻松设置默认电机,其内容如下:

defaultMotor.Voltage = 48.0;
defaultMotor.Torque = 100;

等等,然后我就可以轻松分配:

processingStation(1).FeedstockMotor = defaultMotor;

我想要一小部分允许的电机,能够为这些电机设置非常详细的配置,然后能够使用它们。

我还希望能够跨多个细分市场进行切片,这样我就可以快速获取操作扭矩、电压等列表,用于视觉趋势或其他 HMI 显示。我宁愿不必遍历所有 processingStation 元素来获取我需要的数据。

【问题讨论】:

标签: matlab data-structures vectorization matlab-struct


【解决方案1】:

您需要先将processingStation.FeedstockMotor 转换为结构数组,然后才能访问结果数组的Voltage 字段。

tmp = [processingStation.FeedstockMotor];
result = [tmp.Voltage];

我的路径上有一个函数,允许我像这样实际访问这些子结构

function output = rgetfield(S, field)
    % Split the fieldname on "."
    parts = regexp(field, '\.', 'once', 'split');

    output = [S.(parts{1})];

    if numel(parts) > 1
        % If there are more parts, recursively get them
        output = rgetfield(output, parts{2});
    end
end

然后你可以像这样使用这个函数

values = rgetfield(processingStation, 'FeedstockMotor.Voltage');

【讨论】:

  • 我不太喜欢使用这样的临时变量,但我想这不是世界末日——我可以使用FeedstockMotors = [processingStation.FeedstockMotor]; 之类的东西来获取一组所有电机我关心然后访问子字段组; voltages = [FeedstockMotors.Voltage];currents = [FeedstockMotors.Current]; 等。同样,它仍然是一个临时变量,但这看起来是实现我想要的最清晰/最易读的方式,而且很重要。
  • @Chuck 在这种情况下,临时变量并没有太大的危害。话虽如此,我只是添加了一个用于经常访问子结构的函数。
猜你喜欢
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多