【问题标题】:Finding the index of a specific value in a cell in MATLAB在 MATLAB 中查找单元格中特定值的索引
【发布时间】:2012-11-11 14:47:39
【问题描述】:

我有一个二维单元格,其中每个元素要么是 a) 空,要么是 b) 一个不同长度的向量,其值范围为 0 到 2。我想获取出现某个值的单元格元素的索引或更好的是,每次出现某个值的“完整”索引。

我目前正在研究基于代理的疾病传播模型,这样做是为了找到受感染代理的位置。

提前致谢。

【问题讨论】:

    标签: matlab indexing find cell


    【解决方案1】:

    我会这样做:

    % 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/32bit w/ Intel Core i3-2310M@2.10GHz w/ Ubuntu 11.10/2.6.38-13 上。这主要是由于循环上的 JIT(以及似乎实现了非常糟糕的cellfun 和匿名函数,mumblemumble..)

    无论如何,简而言之,使用循环:它的可读性更好,并且比矢量化解决方案快一个数量级。

    【讨论】:

    • 很好的答案;随着 JIT 的改进,我认为 cellfun 和等价物的使用会减少。现在不得不尝试几种不同的方法以查看哪种方法最快可能会非常烦人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多