matlab:在单元格数组中查找和替换矩阵元素

时间:2017-04-16 20:55:55

标签: matlab cell-array matrix-indexing

我有一个包含多个不同大小矩阵的单元格数组。我想找到&用条件替换矩阵的所有元素,例如将所有1替换为0。我从find and replace values in cell array找到了一个临时解决方案,但它应该更复杂:

示例:

A = {[1 2;3 4] [1 2 3;4 5 6;7 8 9]}
replacement = 1:9;
replacement(replacement==1)=0;
A = cellfun(@(x) replacement(x) ,A,'UniformOutput',false)
A{:}

ans =

 0     2
 3     4

ans =

 0     2     3
 4     5     6
 7     8     9

所以它有效,但我觉得如果没有先指定替换值列表然后“交换”所有元素,这应该是可行的。 (我必须做很多事情并且条件更复杂)。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

一种方法是elementwise-multiplication使用此类1s -

的掩码
cellfun(@(x) (x~=1).*x, A, 'uni',0)

示例运行 -

>> celldisp(A)  % Input cell array
A{1} =
     3     2
     1     4
A{2} =
     7     1     3
     4     5     1
     7     8     9
>> C = cellfun(@(x) (x~=1).*x, A, 'uni',0);
>> celldisp(C)
C{1} =
     3     2
     0     4
C{2} =
     7     0     3
     4     5     0
     7     8     9

通用案例:为了使其可以替换任何其他数字的任何数字,我们需要稍作修改,如此 -

function out = replace_cell_array(A, oldnum, newnum)

out = cellfun(@(x) x+(x==oldnum).*(newnum-oldnum), A, 'uni',0);

样品运行 -

>> A = {[1 2;3 5] [1 2 3;5 5 3;7 8 9]}; % Input cell array
>> celldisp(A)
A{1} =
     1     2
     3     5
A{2} =
     1     2     3
     5     5     3
     7     8     9
>> celldisp(replace_cell_array(A,1,0)) % replace 1s with 0s
ans{1} =
     0     2
     3     5
ans{2} =
     0     2     3
     5     5     3
     7     8     9
>> celldisp(replace_cell_array(A,3,4)) % replace 3s with 4s
ans{1} =
     1     2
     4     5
ans{2} =
     1     2     4
     5     5     4
     7     8     9

答案 1 :(得分:1)

cellfun与匿名函数一起使用具有匿名函数can only contain a single statement的限制。所以它不能为矩阵的一个条目赋值(除非你采用丑陋的,不推荐的技巧)。

为避免这种情况,您可以使用for循环。这不一定比cellfun慢。事实上,它可能会更快一些,并且可以说更具可读性:

A = {[1 2;3 4] [1 2 3;4 5 6;7 8 9]}
repl_source = 1;
repl_target = 0;
for k = 1:numel(A)
    A{k}(A{k}==repl_source) = repl_target;
end