在 Matlab 中结合 cellfun 和 subs

Combine cellfun and subs in Matlab

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

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() 是符号数学工具箱的一部分,它 returns 符号数组。请注意,此函数甚至不会替换为 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);

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

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

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

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

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

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

编辑:

以下难以理解的一行将 Matrix 指示的 CellArray 的元素替换到位:

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