【问题标题】:Matlab: Assigning same value to (different) fields in the same position of a struct arrayMatlab:为结构数组相同位置的(不同)字段分配相同的值
【发布时间】:2015-01-30 02:06:28
【问题描述】:

假设我有一个 1x10 结构 my_struct 有两个字段:fieldAfieldB

我应该如何以更直接的形式为所有字段的特定位置分配一个标量数字(或任何其他实体)?

换句话说,有没有办法做到这一点:

my_struct(5).fieldA = pi;
my_struct(5).fieldB = pi;

以这样的方式:my_struct(5).* = pimy_struct(5) = deal(pi)?

【问题讨论】:

    标签: arrays matlab struct field variable-assignment


    【解决方案1】:

    您可以使用fieldnamescell2struct 的组合以编程方式构建所有字段中具有相同值的结构,然后执行完整结构分配。

    function out = setAllFields(s, value)
    %SETALLFIELDS Build a scalar struct from template, replacing all field values
    % Where s is your template struct, and value is the value desired in all fields
    out = cell2struct(repmat({value}, [numel(fieldnames(s)) 1]), fieldnames(s));
    

    定义该函数后,您可以像这样使用单个或多个目标索引进行赋值。

    my_struct(5) = setAllFields(my_struct, pi);
    my_struct([2 4:6]) = setAllFields(my_struct, 'foo');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      相关资源
      最近更新 更多