找到以下值并在矩阵中表示它们的出现

时间:2016-09-12 12:33:33

标签: matlab matrix

我有一个矩阵A

A = [23  34  45   0    0    0 ;
     21  34   0   0   23   11 ;
     34  23   0   0    0   22 ;
     23  11  21   0    0   45 ;
     11  45  23   0    0    0 ]

我在矩阵中找到了唯一的值:

U = unique(A) = [0; 11; 21; 22; 23; 34; 45]

排除值0,我想要一个矩阵6x6(6是找不到零的值的数量),其中我想表示值​​从每行中的另一个值开始跟随的次数。

例如:

11之后,110
11之后,211的出现。
11之后,220的出现。
11之后,230的出现。
11之后,340的出现。
11之后45 1B = [0 1 0 0 0 1]

所以我想要的矩阵的第一行是:21

11之后,021
21之后,021的出现。
22之后,021的出现。
23之后,021的出现。
34之后,121的出现。
45之后1 B = [0 1 0 0 0 1; 0 0 0 0 1 1; ...] U

所以矩阵的第二行是

{{1}}

我想对{{1}}中的所有值重复相同的过程。

你能帮助我吗?

2 个答案:

答案 0 :(得分:4)

这是一个可能的解决方案:

A = [23  34  45   0    0    0 ;
     21  34   0   0   23   11 ;
     34  23   0   0    0   22 ;
     23  11  21   0    0   45 ;
     11  45  23   0    0    0 ]
% final result is a 6 * 6 table we want to map from 11; 21; 22; 23; 34; 45 to 1:6
% first  sort the array
[S SI] = sort(A(:));
% then generate mapped values corresponding to original values
S2=[0; (cumsum(diff(S)>0))];
% then replace original with mapped value
A(SI) = S2;
% use circshift to create a matrix that brings next element in each row to one left ,
% so current value in original matrix and next value in cricshifted matrix are in the same position.
C=circshift(A,[0,-1]);
% so both matrices converted to vectors and horizontally concatenated to a n * 2 matrix (U) ,
% its first column is the current element in each row and second column is the following element.
% since for example there may be multiple cases of [11 21] ,
% we take unique of the U matrix to remove repeated co-occurances.
U =  unique( [A(1:end-size(A,1)); C(1:end-size(A,1))]','rows');
% zero values should be discarded then we get indices of rows that contain zero
[ro ,~] = find(U == 0);
uro = unique(ro);
% rows that contain zero excluded from two column matrix (U).
U(uro,:) =[];
% now first column of U contains indices of rows of 1s and second column indices of their columns.
% then convert indices to 0-1 matrix
result = full(sparse(U(:,1),U(:,2),1))

答案 1 :(得分:1)

因为我正在使用sans-compiler,所以可能会在这里的某个地方拼错,但一般策略是:创建蒙版,应用蒙版,计数

U = U(2:end); %Remove 0 value from unique matrix

output = zeros(length(U));

for ii = 1:length(U)
    maskA = cumsum(A == U(ii),2); #Find any values of A = U(ii), and make them + all to the right equal to 1
    maskA = [zeros(size(A,1),1) maskA(:,1:size(A,2)-1)] %Shift highlighting to the right one column
    maskedA = A*maskA; %Filter out only values we want to count
    for kk = 2:length(U)
        output(ii,jj) = sum(maskedA(:)==U(ii)); %Count number of matching values
    end
end