2016-09-26 42 views
0

我需要一些帮助。我有一个数组,如下所示,6行5列,任何一行中的元素都不重复。这些元素都是单个数字。 我想知道,每行,当一个数字,比如说1出现时,我想要保持该行其他数字出现的频率。例如,1在第1,3,5行中出现3次。 1出现时,2出现一次,3出现两次,4出现两次,5出现一次,6出现两次,7出现一次,8出现三次,以及9出现零次。我想保留这个信息,这将是什么样子,V = [3,1,2,2,1,2,1,3,0]载体,通过与像N = [1,2,3,4,5,6,7,8,9]MATLAB - 有条件的数组元素的频率

ARRAY = 
    1  5  8 2 6 
    2  3  4 6 7 
    3  1  8 7 4 
    6  5  7 9 4 
    1  4  3 8 6 
    5  7  8 9 6 

矢量开始下面我有没有给我找的,有人可以帮助请反馈的代码?谢谢

for i=1:length(ARRAY) 
    for j=1:length(N) 
     ARRAY(i,:)==j 
     V(j) = sum(j)   
    end 
end 

回答

0

我不明白你是如何解决你的示例代码的问题,但这是应该工作的东西。这使用findanyaccumarray和在每次迭代的循环它将返回一个V对应于第i个元素中N

for i=1:length(N) 
    rowIdx = find(any(A == N(i),2)); % Find all the rows contain N(j) 
    A_red = A(rowIdx,:); % Get only those rows 
    V = [accumarray(A_red(:),1)]'; % Count occurrences of the 9 numbers 
    V(end+1:9) = 0; % If some numbers don't exist place zeros on their counts 
end 
1

使用指数即在A CREAE零和一个6 * 9矩阵[如果i的第i行包含j,则其i,j]个元素是1。

然后乘以零和一矩阵与其转置来获得期望的结果:

A =[... 
    1  5  8 2 6 
    2  3  4 6 7 
    3  1  8 7 4 
    6  5  7 9 4 
    1  4  3 8 6 
    5  7  8 9 6] 
% create a matrix with the size of A that each row contains the row number 
rowidx = repmat((1 : size(A,1)).' , 1 , size(A , 2)) 
% z_o a zero and one 6 * 9 matrix that [i,j] th element of it is 1 if i th row of A contains j 
z_o = full(sparse(rowidx , A, 1)) 
% matrix multiplication with its transpose to create desirable result. each column relates to number N 
out = z_o.' * z_o 

结果:每一列涉及N-

3 1 2 2 1 2 1 3 0 
    1 2 1 1 1 2 1 1 0 
    2 1 3 3 0 2 2 2 0 
    2 1 3 4 1 3 3 2 1 
    1 1 0 1 3 3 2 2 2 
    2 2 2 3 3 5 3 3 2 
    1 1 2 3 2 3 4 2 2 
    3 1 2 2 2 3 2 4 1 
    0 0 0 1 2 2 2 1 2 
+0

尼斯特技,这避免了'for循环'! –