How to use ismember in a cell array?

81 visualizaciones (últimos 30 días)
Dominik Mattioli
Dominik Mattioli el 21 de Feb. de 2017
Editada: Emmanuel Lasso el 6 de Oct. de 2019
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'."

Respuesta aceptada

Jan
Jan el 21 de Feb. de 2017
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 comentario
Jan
Jan el 21 de Feb. de 2017
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.

Iniciar sesión para comentar.

Más respuestas (1)

Stephen23
Stephen23 el 21 de Feb. de 2017
Editada: Stephen23 el 21 de Feb. de 2017
>> 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 comentarios
Dominik Mattioli
Dominik Mattioli el 21 de Feb. de 2017
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 el 6 de Oct. de 2019
Editada: Emmanuel Lasso el 6 de Oct. de 2019
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

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by