How to use ismember in a cell array?

63 次查看(过去 30 天)
I would like to change the value of some value within a cell array that has only numeric data, preferably not using loops because I will be performing this operation with large cell arrays many times.
% Given:
A = {[1 2 3] [3 4 5 6];[7 8] [9 1 2 3 4];[5] [6 7 8 9]};
B = 1;
% Set all values in A equal to B as NaN.
% If A were a double then it would look like this:
A(ismember(A,B)) = NaN;
I've been trying to use this
A(cellfun(@(x) x == B(1),A,'un',0))
But I get this error:
"Function 'subsindex' is not defined for values of class 'cell'."

采纳的回答

Jan
Jan 2017-2-21
Try it with loops, because there is no general rule that loops are slow:
A = {[1 2 3] [3 4 5 6];[7 8] [9 1 2 3 4];[5] [6 7 8 9]};
B = 1;
for iA = 1:numel(A)
tmpA = A{iA};
tmpA(tmpA == B) = NaN;
A{iA} = tmpA;
end
Measure the timings using timeit or tic/toc. cellfun with anonymous function is not really fast also, because handling the anonymos function for each element needs some time, perhaps more than the loop overhead.
  1 个评论
Jan
Jan 2017-2-21
Note that strrep is very efficient with replacing characters in cell strings. Unfortunately this command does not accept numerical values as e.g. strfind does. But a C-Mex might be much faster, so consider to mex this, if it is the bottleneck of your code.

请先登录,再进行评论。

更多回答(1 个)

Stephen23
Stephen23 2017-2-21
编辑:Stephen23 2017-2-21
>> A = {[1,2,3],[3,4,5,6];[7,8],[9,1,2,3,4];[5],[6,7,8,9]};
>> B = 1;
>> C = cellfun(@(a)a~=B,A,'Uni',0);
>> D = cellfun(@(a,c)a.*(c./c),A,C,'Uni',0);
>> D{:}
ans =
NaN 2 3
ans =
7 8
ans = 5
ans =
3 4 5 6
ans =
9 NaN 2 3 4
ans =
6 7 8 9
  2 个评论
Dominik Mattioli
Dominik Mattioli 2017-2-21
This is what I expected, however Jan's right about the loops. For my code, a loop was faster. Must be the overhead of cellfun. Thanks though!
Emmanuel Lasso
Emmanuel Lasso 2019-10-6
编辑:Emmanuel Lasso 2019-10-6
And if I want to replace a value of an array, i mean, in this case B = [3 2 1 0], and C should find the values that match from A, A variates between 3 and 0 like randi function, so how D can use cellfun for search in A the values that match and replace with another values?. For example if a~=3 then replace it with -3

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by