필터 지우기
필터 지우기

How to use ismember in a cell array?

조회 수: 88 (최근 30일)
Dominik Mattioli
Dominik Mattioli 2017년 2월 21일
편집: Emmanuel Lasso 2019년 10월 6일
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에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by