Searching the index of a specific value in a cell in MATLAB

I have a two-dimensional cell where each element is either a) empty or b) a variable-length vector with values ​​from 0 to 2. I would like to get the indices of the elements of the cell where a certain value occurs, or better yet, the "full" index of each occurrence a certain value.

I am currently working on an agent-based model for the spread of the disease, and this is done in order to find the positions of infected agents.

Thanks in advance.

+4
source share
1 answer

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.

+5
source

Source: https://habr.com/ru/post/1447891/


All Articles