找到二维阵列中岛屿长度的分布?

时间:2016-11-11 06:51:30

标签: arrays matlab matrix

我将用一个例子来解释我的问题。想象一下,你有一个如下所示的二维矩阵:

5 4 3 8 0 0
5 4 2 9 1 0
5 6 2 7 2 0
5 4 7 9 0 0
5 6 7 1 2 0

按岛屿我的意思是相同元素的列组(零除外)。 我想找到长度为islands的直方图,除了由零元素组成的直方图。

enter image description here

此矩阵有

island-length occurrence
  5               1
  2               3
  1               12

如何使用Matlab实现此任务?

2 个答案:

答案 0 :(得分:2)

也许有更短的可能性,但这样做 - 它完全被矢量化:

A = [5 4 3 8 0 0
     5 4 2 9 1 0
     5 6 2 7 2 0
     5 4 7 9 0 0
     5 6 7 1 2 0]

%// pad zeros to first line of A
X(2:size(A,1)+1,:) = A;

%// differences of X
dX = diff(X)

%// cumulative sum of "logicalized" differences
cs = cumsum(logical(dX(:)))
%// filter out zeros
cs = cs(logical(A(:)))
%// count occurances
aa = accumarray(cs,1)

%// unique occurances
uaa = unique(aa)
%// count unique occurances
occ = hist(aa,uaa).'
%// accumarray may introduce new zeros, filter out
mask = logical(uaa)

%// output
out = [occ(mask) uaa(mask)]
out =

    12     1
     3     2
     1     5

答案 1 :(得分:1)

需要对我的一个旧片段稍作修改以过滤掉零。你走了:

% Your Matrix
A = [ 5 4 3 8 0 0;
5 4 2 9 1 0;
5 6 2 7 2 0;
5 4 7 9 0 0;
5 6 7 1 2 0];

% Find Edges (Ends of Islands)
B = diff(A);
B = [ones(1,size(A,2));B~=0;ones(1,size(A,2))];

% At each column, find distances between island edges, filter out zero islands.
R = cell(size(A,2),1);
for i = 1:size(A,2)
    [C ~] = find(B(:,i));
    Ac = A(C(1:end-1),i);
    D = diff(C);
    D(Ac==0)=[];
    R{i} = D;
end

% Find histogram of island lengths
R = R(find(~cellfun(@isempty,R)),1);
R = cell2mat(R);
[a,~,c] = unique(R);
out = [a, accumarray(c,ones(size(R)))];