【问题标题】:Is there a version of bsxfun that works on structure arrays?是否有适用于结构数组的 bsxfun 版本?
【发布时间】:2016-11-06 00:05:41
【问题描述】:

为什么我可以这样做:

a = [1 2];
b = [3 4];
bsxfun(@(ai,bj) ai + bj, a, b')
% 4     5
% 5     6

但不是这个:

a = struct('x', {1 2});
b = struct('x', {3 4});
bsxfun(@(ai,bj) ai.x + bj.x, a, b');
% Error using bsxfun
% Operands must be numeric arrays.

是否存在适用于这两种情况的替换函数?

【问题讨论】:

    标签: matlab struct bsxfun


    【解决方案1】:

    这可能不是一个通用的解决方案*,但对于您的特定示例,通过使用comma-separated-list generator syntax,很容易将您的结构数组转换为数值数组inside bsxfun ,然后使用您原来的匿名函数,即

    >> bsxfun(@(ai, bj) ai+bj, [a.x], [b.x]')
    ans =
         4     5
         5     6
    

    这仍应利用 bsxfun 赋予的计算效率(例如,与慢得多的“repmat+arrayfun”方法相反)。


    *例如如果您的字段包含数组而不是标量,它可能无法按预期工作,因为扩展为逗号分隔列表会有所不同

    【讨论】:

    • 不幸的是,我这样做的原因是使用结构中的两个字段
    • 好吧,根据您的问题的确切性质,如果您的字段格式正确,您仍然可以使用此技术。你想做什么?
    【解决方案2】:

    一个 hacky 解决方法:

    function res = bsxfun_struct(f, A, B)
        % best way to ensure our output size matches the behaviour of bsxfun is just to call it
        dummy = bsxfun(@(ai, bj) ai+bj, zeros(size(A)), zeros(size(B)));
        res_size = size(dummy);
    
        % repeat the matrices as needed
        Arep = repmat(A, res_size ./ size(A));
        Brep = repmat(B, res_size ./ size(B));
    
        % now we can just apply the function pairwise
        res = arrayfun(f, Arep, Brep);
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多