Find indices in cell array
9 次查看(过去 30 天)
显示 更早的评论
Hello everybody,
I have some problems to get the indices of a certain value, in this case -1, within a cell array. The structure of the cell array is like this: A is a 27x1 cell where each of the 27 rows has 500000 cell entries (numeric values between -1 and 999). What I want are the indices where the value -1 occurs, since I have to replace them afterwards. For example A{1,1}{4,1} or A{24,1}{95423,1} are containing the value -1. First of all I tried index=cellfun(@(x) x==-1, A{1,1}, 'Uniform', false) and then I used index2=cellfun(@(x) x==-1, A{2,1}, 'Uniform', false) and so on (. So I could get the information separately but I think there should exist a solution where I don't have to define 27 index cell arrays. Hopefully someone can help and recommend a more meaningful solution. I used the search function but none of the solutions in similar topics did work for my case (using cellfun(@(x) find(x==-1), A{1,1}, 'UniformOutput',false) leads to the same approach like I did it already for example).
Thanks in advance :)
0 个评论
回答(3 个)
Andrei Bobrov
2017-10-25
Aw = cellfun(@(x)[x{:}]',A,'un',0);
Aw = [Aw{:}];
[ii,jj] = find(Aw == -1) ;
out = [jj,ii];
7 个评论
Jos (10584)
2017-10-25
A = {[-1 0 0 -1],1:4,[1 -1 1 -1 1 -1]} % example array
fhFind = @(x) find(x == -1) ;
IDX = cellfun(fhFind ,A,'un',0)
0 个评论
Jan
2017-10-25
编辑:Jan
2017-10-25
After the data are converted to a numerical array, the processing is very efficient. Consider, if it would be better to store the data as numerical array directly instead of the complicated nested cell.
If you really need the cells, and want to replace the -1 only, it might be better to avoid the conversion to one huge numerical array:
for iA = 1:numel(A)
B = A{iA};
for iB = 1:numel(B)
C = B{iB};
C(C == -1) = 42;
B{iB} = C;
end
end
This is not nice, but it is worth to try if it is faster.
7 个评论
Jan
2017-10-28
@Tima: You have set all values of the output to {-99} in this line already:
union{i,1}(:,2)={-99};
and later crop of all other information:
union2{i,1}=union{i,1}(:,2);
Therefore it is not clear to me, what you want to achieve.
另请参阅
类别
在 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!