计算向量中的共现邻居

时间:2014-07-13 10:51:35

标签: matlab

我有一个向量:例如S =(0,3,2,0,1,2,0,1,1,2,3,3,0,1,2,3,0)。 我想计算共现邻居,例如第一个邻居" o,3"直到序列结束才发生了多少次?然后它调查下一对" 2,0"并且类似地为其他对做。 以下是我的代码的一部分:

s=size(pic);
S=s(1)*s(2);
V = reshape(pic,1,S);
min= min(V);
Z=zeros(1,S+1);
Z(1)=min;
Z(2:end)=V;
for i=[0:2:length(Z)-1];
contj=0
    for j=0;length(Z)-1;

        if  Z(i,i+1)= Z(j,j+1) 
            contj=contj+1

        end 

    end
    count(i)= contj
end

它给了我这个错误:

The expression to the left of the equals sign is not a valid target for an assignment

在这一行:

if  Z(i,i+1)= Z(j,j+1) 

我读了类似的问题并应用了相关提示,但它们没有用!

2 个答案:

答案 0 :(得分:2)

如果对定义而没有重叠(根据评论):

S = [0,3,2,0,1,2,0,1,1,2,3,3,0,1,2,3]; %// define data
S2 = reshape(S,2,[]).'; %'// arrange in pairs: one pair in each row
[~, jj, kk] = unique(S2,'rows'); %// get unique labels for pairs
pairs = S2(jj,:); %// unique pairs
counts = accumarray(kk, 1); %// count of each pair. Or use histc(kk, 1:max(kk))

示例:如上所述S(我引入空白以使对子脱颖而出),

S = [0,3, 2,0, 1,2, 0,1, 1,2, 3,3, 0,1, 2,3];

结果是

pairs =
     0     1
     0     3
     1     2
     2     0
     2     3
     3     3

counts =
     2
     1
     2
     1
     1
     1

如果对定义没有重叠但计算重叠:

S = [0,3,2,0,1,2,0,1,1,2,3,3,0,1,2,3]; %// define data
S2 = reshape(S,2,[]).'; %'// arrange in pairs: one pair in each row
[~, jj] = unique(S2,'rows'); %// get unique labels for pairs
pairs = S2(jj,:); %// unique pairs
P = [S(1:end-1).' S(2:end).']; %// all pairs, with overlapping
counts = sum(pdist2(P,pairs,'hamming')==0);

如果您没有pdist2(统计工具箱),请将最后一行替换为

counts = sum(all(bsxfun(@eq, pairs.', permute(P, [2 3 1]))), 3);

结果:

>> pairs
pairs =
     0     1
     0     3
     1     2
     2     0
     2     3
     3     3
>> counts
counts =
     3     1     3     2     2     1

答案 1 :(得分:0)

使用sparse命令

执行此操作
os = - min(S) + 1; % convert S into indices 
% if you want all pairs, i.e., for S = (2,0,1) count (2,0) AND (0,1):
S = sparse( S(1:end-1) + os, S(2:end) + os, 1 );
% if you don't want all pairs, i.e., for S = (2,0,1,3) count (2,0) and (1,3) ONLY:
S = sparse( S(1:2:end)+os, S(2:2:end) + os, 1 );
[f s c] = find(S);
f = f - os; % convert back
s = s - os;

共同出现及其计数在成对(f,s) - c

>> [f s c]
ans =

 2     0     2  % i.e. the pair (2,0) appears twice in S...
 3     0     2
 0     1     3
 1     1     1
 1     2     3
 3     2     1
 0     3     1
 2     3     2
 3     3     1