计算数组元素持久性算法

3
我有一个15x15x2200的大型数组。这仅仅是一组15x15的稀疏矩阵,描述了15个节点之间的链接以及它们在2200个时间单位内的变化情况。我需要计算每个链接存在的时间。我的意思是,假设A [4,11]在时间单位5之前为0,在时间单位20保持1,然后变成0,并且在42到46之间再次变成1,我想将这些信息存储在一个数组中,将它们的长度分别存储在LEN = {...15, 4, ....}中。
我正在尝试在MATLAB中完成这项工作,然后生成直方图。最好的方法是什么?
1个回答

4

让我们尝试不使用循环来完成这个任务。

%# random adjacency matrix
array = randi([0 1], [15 15 2200]);

%# get the size of the array
[n1,n2,n3] = size(array);

%# reshape it so that it becomes n3 by n1*n2
array2d = reshape(array,[],n3)';

%# make sure that every run has a beginning and an end by padding 0's
array2d = [zeros(1,n1*n2);array2d;zeros(1,n1*n2)];

%# take the difference. +1 indicates a start, -1 indicates an end
arrayDiff = diff(array2d,1,1);
[startIdx,startCol] = find(arrayDiff==1);
[endIdx,endCol] = find(arrayDiff==-1);

%# since every sequence has a start and an end, and since find searches down the columns
%# every start is matched with the corresponding end. Simply take the difference
persistence = endIdx-startIdx; %# you may have to add 1, if 42 to 46 is 5, not 4

%# plot a histogram - make sure you play with the number of bins a bit
nBins = 20;
figure,hist(persistence,nBins)

编辑:

为了看到您的轨迹的另一种视觉表示方式,请调用

figure,imshow(array2d)

这将在您有一系列链接的任何地方显示白色条纹,并向您展示整体模式。


@Jonas:我稍微格式化了一下代码,让它更易于阅读 :) - Amro
@Amro:抱歉,在您编辑时我可能已经提交了我的编辑。您可以再试一次吗? - Jonas
错了..好的,让我们再试一次! - Amro
谢谢。这与我编写的代码类似。我只是想知道是否有更快的方法。 - Ankur Chauhan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接