Matlab:找到没有循环的NaN的相邻实例

标签 matlab matrix vectorization nan

本质上,我有一个数据矩阵,其中包含许多由 NaN 表示的“漏洞”,我想检索所有 NaN 的索引,这些索引在单个列中聚集少于 4 次。

例如与矩阵:

A = 
    23    12    NaN   56    60    21    NaN
    60    56    94    22    45    NaN   NaN
    23    55    19    83    NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    84    99    43    32    89    12    NaN
    76    92    73    47    22    12    10
    23    55    12    93    61    94    20
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    41    16    83    39    82    37    43
    14    78    92    40    81    29    60

它会返回:

ans = 
    [4; 5; 6; 10; 16; 17; 18; 22; 25; 28; 29; 30; 34; 40; 41; 42; 46; 58; 70; 82]

到目前为止,我有一个向量,其中包含来自

的所有 NaN 值的索引
nan_list=find(isnan(A(:)))

但我不知道如何在不使用循环的情况下从该向量中提取序列号,这太昂贵了。我也尝试了类似于 b3 here 发布的答案的东西,通过将所有 NaN 切换为未出现在矩阵中的值,但该代码不可转移到其他数据集。

感谢您的任何建议!

最佳答案

代码

N = 4; %// Fewer than clusters of N or N+ NaNs are to be detecteed
nan_pos = isnan(A) %// Find NaN positions as a binary array
conv_res = conv2(double(nan_pos),[0 ones(1,N)]')==N %//' Perform convolution
start_ind = find(conv_res(N+1:end,:)) %// Find positions where clusters of N or N+ NaNs start
nan_pos(unique(bsxfun(@plus,start_ind,[0:N-1])))=0 %// Get positions of all those clustered N or N+ NaNs and set them in NaN position array as zeros
out = find(nan_pos) %// Finally the desired output

示例

作为示例,让我们在稍微不同的输入上尝试这段代码,希望能测试问题的各个方面 -

A = [
    23    12    NaN   56    60    21    NaN
    60    56    94    22    45    NaN   NaN
    23    55    19    83    NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    84    99    43    32    89    12    NaN
    76    92    73    47    22    12    10
    23    55    12    93    61    94    20
    NaN   NaN   NaN   NaN   NaN   NaN   NaN
    41    NaN   NaN    39    82    37   43
    14    78    NaN    40    81   NaN   60]

现在,假设我们正在寻找少于 3 个 NaN 的簇索引。因此在代码中将N编辑为3,输出为-

out =
    10    22    23    25    46    58    70    72    82

当我们查看输入时,这是有道理的。

关于Matlab:找到没有循环的NaN的相邻实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24565182/

相关文章:

python - numpy.vectorize : Why so slow?

machine-learning - 如何使用 MATLAB 神经网络工具箱中的自定义神经网络函数

python - 使用 scipy.io.loadmat 从 .mat Matlab 文件将字典键转换为在 Python 中具有相同值的变量名

javascript - 通过连接多个数组来创建列表矩阵

c++ - 在 OpenCV 中将一些行从一个矩阵复制到另一个矩阵的最快方法

python - 使用 numpy vectorize 时如何避免大量额外的内存消耗?

algorithm - 如何为嵌套循环设置变量?

MATLAB scatter3、plot3速度差异

javascript - 运行需要 jsfeat 的 JavaScript 程序

vectorization - 内存库矢量处理器中内存访问冲突的条件