# How to use ismember in a cell array?

141 Ansichten (letzte 30 Tage)
Dominik Mattioli am 21 Feb. 2017
Bearbeitet: Emmanuel Lasso am 6 Okt. 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]; [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'."
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Jan am 21 Feb. 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]; [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 KommentarKeine anzeigenKeine ausblenden
Jan am 21 Feb. 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.

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Stephen23 am 21 Feb. 2017
Bearbeitet: Stephen23 am 21 Feb. 2017
>> A = {[1,2,3],[3,4,5,6];[7,8],[9,1,2,3,4];,[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 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Emmanuel Lasso am 6 Okt. 2019
Bearbeitet: Emmanuel Lasso am 6 Okt. 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

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Cell Arrays in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!