Here's how I would do it:
% some example data A = { [], [], [3 4 5] [4 8 ], [], [0 2 3 0 1] }; p = 4; % value of interest % Finding the indices: % ------------------------- % use cellfun to find indices I = cellfun(@(x) find(x==p), A, 'UniformOutput', false); % check again for empties % (just for consistency; you may skip this step) I(cellfun('isempty', I)) = {[]};
Call this method 1.
A loop is also possible:
I = cell(size(A)); for ii = 1:numel(I) I{ii} = find(A{ii} == p); end I(cellfun('isempty',I)) = {[]};
Call this method 2.
Comparison of two methods for such a speed:
tic; for ii = 1:1e3, [method1], end; toc tic; for ii = 1:1e3, [method2], end; toc
gives
Elapsed time is 0.483969 seconds. % method1 Elapsed time is 0.047126 seconds. % method2
on Matlab R2010b / 32bit with Intel Core i3-2310M@2.10GHz with Ubuntu 11.10 / 2.6.38-13. This is mainly due to JIT on loops (and how terribly cellfun and anonymous functions seem to be implemented, mumblemumble ..)
In any case, use a loop: it reads better and is an order of magnitude faster than a vector solution.
source share