我是这样做的:
% 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)) = {[]};
Run Code Online (Sandbox Code Playgroud)
调用此方法1.
循环也是可能的:
I = cell(size(A));
for ii = 1:numel(I)
I{ii} = find(A{ii} == p);
end
I(cellfun('isempty',I)) = {[]};
Run Code Online (Sandbox Code Playgroud)
调用此方法2.
比较两种速度方法如下:
tic; for ii = 1:1e3, [method1], end; toc
tic; for ii = 1:1e3, [method2], end; toc
Run Code Online (Sandbox Code Playgroud)
给
Elapsed time is 0.483969 seconds. % method1
Elapsed time is 0.047126 seconds. % method2
Run Code Online (Sandbox Code Playgroud)
在Matlab R2010b/32bit w/Intel Core i3-2310M@2.10GHz w/Ubuntu 11.10/2.6.38-13.这主要是由于JIT on循环(以及如何实现可怕的cellfun匿名函数,mumblemumble ..)
无论如何,简而言之,使用循环:它更易读,比矢量化解决方案快一个数量级.