簡體   English   中英

計算向量中的同現鄰居

[英]count co-occurrence neighbors in a vector

我有一個向量:例如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) 

我閱讀了類似的問題,並在其上應用了提示,但它們沒有起作用!

如果定義的對沒有重疊 (根據注釋):

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 (統計信息工具箱), 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

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  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM