在MATLAB中查找单元格中特定值的索引

use*_*941 4 indexing matlab find cell

我有一个二维单元格,其中每个元素都是a)空或b)一个不同长度的矢量,其值范围从0到2.我想获得某个值出现或更好的单元格元素的索引,某个值的每次出现的"完整"索引.

我目前正在研究一种基于药剂的疾病传播模型,这样做是为了找到感染药物的位置.

提前致谢.

Rod*_*uis 5

我是这样做的:

% 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 ..)

无论如何,简而言之,使用循环:它更易读,比矢量化解决方案快一个数量级.

  • 很好的答案; 随着JIT的改进,我认为我们将看到`cellfun`和等价物的用量减少.现在,为了看看哪种方式最快,必须尝试几种不同的方法,这可能会非常恼人. (2认同)