【问题标题】:MATLAB: How to use cellfun with a struct?MATLAB:如何将 cellfun 与结构一起使用?
【发布时间】:2018-07-08 06:20:04
【问题描述】:

想象一个由相同结构(在布局方面)组成的元胞数组,如下面的示例cellArray。如何将cellfun 应用于这些结构的特定字段?

cellArray{1,1}.val1 = 10;
cellArray{1,1}.val2 = 20;
cellArray{1,2}.val1 = 1000;
cellArray{1,2}.val2 = 2000;

如何使用 cellfun 将值 50 添加到所有单元格,但仅添加到字段 val2

out = cellfun(@plus, cellArray?????, {50, 50}, 'UniformOutput', false);

【问题讨论】:

  • 文档是否提到了这种特殊情况?

标签: matlab struct cell-array


【解决方案1】:

您可以编写自定义函数add_val2(x, y),将y 添加到字段x.val2,并使用@add_val2 而不是@plus 调用cellfun()

首先,创建函数add_val2.m

function x = add_val2(x, y)
    x.val2 = x.val2 + y;
end

那么,调用cellfun()就这么简单

out = cellfun(@add_val2, cellArray, {50, 50}, 'UniformOutput', false);

导致

>> out{1}
ans = 
  struct with fields:
    val1: 10
    val2: 70

>> out{2}
ans = 
  struct with fields:
    val1: 1000
    val2: 2050

【讨论】:

    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多