【问题标题】:Combine cellfun and subs in Matlab在 Matlab 中结合 cellfun 和 subs
【发布时间】:2016-02-09 21:40:15
【问题描述】:

我有一些值存储在矩阵中,例如

Matrix = [1,4,6]

还有一个元胞数组,如:

CellArray{1} = [0,0,1,0]
...
CellArray{4} = [0,0,0,0,0,0,0,1]
...
CellArray{6} = [0,0,1,1,1,0]

对于 CellArray 中矩阵的每个元素,即 CellArray{Matrix(1:end)},我想用零替换那些元素。到目前为止,我已经想到了:

[Output] = cellfun(@(x) subs(x,1,0),{CellArray{Matrix}},'UniformOutput',false)

虽然,输出不是我想要的......

【问题讨论】:

  • subs 不是你想的那样,试试subs([2,3,4],2,1)。您正在做的事情可能会起作用,但我不确定匿名函数将如何为您完成替换
  • @AndrasDeak,我认为就像在您的示例数组中一样,所有 2 都被替换为 1,结果是 [1,3,4]
  • @AndrasDeak 2015b :)
  • 如果我理解正确的话,您应该可以使用@(x) double(subs(x,1,0)) 转换为数值数组。
  • 它更改为符号,因为它是一个符号函数,旨在处理符号数组。它适用于纯数字数组(正如您所见,它不适用于我),这是一个小奇迹。这是对该函数的强烈意外使用,因此您应该期待一些奇怪的事情。

标签: arrays matlab substitution cell-array


【解决方案1】:

由于该示例表明CellArray 仅包含具有0s 和1s 的向量(并且问题没有指定相反),我可以建议

Output = cellfun(@(x)zeros(1, numel(x)), CellArray(Matrix), 'uniformoutput', 0)

实际上只是用适当长度的零向量替换条目。

【讨论】:

  • 就我而言,只有0s 和1s 存在,这个答案是完美的。消除了subs 问题,易于理解/实现。
【解决方案2】:

正如我们在 cmets 中解决的那样,问题在于 subs() 是符号数学工具箱的一部分,它返回符号数组。请注意,此函数甚至不会替换为 R2012b 中的数值数组,但您使用的是 R2015b,它可以。

所以解决方案是在cellfun 中显式转换为数值数组:

[Output] = cellfun(@(x) double(subs(x,1,0)),{CellArray{Matrix}},'UniformOutput',false);

或者,由于符号数学真的很慢,也许同样低效的基于字符串的解决方案可能具有竞争力:

oddrep = @(x) str2num(regexprep(num2str(x),'1','0'));
[Output] = cellfun(oddrep,{CellArray{Matrix}},'UniformOutput',false);

【讨论】:

    【解决方案3】:

    抛开诙谐的回答,还有subsasgn 的方法:

    Output = cellfun(@(x)subsasgn(x, struct('type','()', 'subs',{{find(x==1)}}), 0), CellArray(Matrix), 'uniformoutput', 0);
    

    这适用于存在非零和非一条目的情况。它也应该比字符串或符号方法更快。 并且应该可以对其进行修改,以便就地修改 CellArray 的条目。

    编辑:

    以下难以消化的单行替换了CellArray 中由Matrix 指示的元素:

    CellArray = subsasgn(CellArray, struct('type', '()', 'subs', {{Matrix}}), cellfun(@(x)subsasgn(x, struct('type','()', 'subs',{{find(x==1)}}), 0), CellArray(Matrix), 'uniformoutput', 0))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2012-10-28
      • 2014-08-03
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多