2012-11-23 180 views
4

我有一個二維單元格,其中每個元素都是a)空的或b)具有範圍從0到2的值的不同長度的矢量。我想要獲得出現特定值或甚至更好的單元格元素的索引,每個特定值出現的「完整」索引。在MATLAB中查找單元格中特定值的索引

我目前正在研究基於代理的疾病擴散模型,這是爲了找到感染代理的位置。

在此先感謝。

回答

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)) = {[]}; 

調用此方法1。

環路也是可能的:

I = cell(size(A)); 
for ii = 1:numel(I) 
    I{ii} = find(A{ii} == p); 
end 
I(cellfun('isempty',I)) = {[]}; 

調用此方法2。

比較兩種方法的速度,像這樣:

tic; for ii = 1:1e3, [method1], end; toc 
tic; for ii = 1:1e3, [method2], end; toc 

Elapsed time is 0.483969 seconds. % method1 
Elapsed time is 0.047126 seconds. % method2 
基於Matlab R2010b中位/ 32位

瓦特/英特爾酷睿[email protected] W/Ubuntu的11.10/2.6。 38-13。這主要是由於JIT on循環(以及cellfun和匿名函數似乎是如何實現的,嘟.. ......)

無論如何,總之,使用循環:它更好的可讀性,並且比矢量化解決方案。

+2

很好的回答;隨着JIT的提高,我認爲我們會看到'cellfun'和等價物的用處不大。現在必須嘗試幾種不同的方法才能看出哪種方法最快,這可能非常令人惱火。 –

相關問題