How to use ismember in a cell array?
64 ビュー (過去 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'."
0 件のコメント
採用された回答
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
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
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 件のコメント
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 Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!