简体   繁体   English

从矩阵M,如何找到向量Vi的像元,该向量指示每列Ci中值2的索引线?

[英]From the matrix M, how to find the cell of vectors Vi, indicating the index line of the value 2 in each column Ci?

From the matrix M, how to find the cell of vectors Vi, indicating the index line of the value 2 in each column Ci ? 从矩阵M,如何找到向量Vi的像元,该向量指示每列Ci中值2的索引线?

Example: 例:

M=[1 0 2 0;
   0 2 2 1;
   2 1 0 2;
   2 1 2 0;
   0 2 1 1]

The expected output: {[3 4],[2 5],[1 2 4],[3]} 预期输出: {[3 4],[2 5],[1 2 4],[3]}

You can use a combination of find in concert with accumarray : 您可以结合使用findaccumarray

[row,col] = find(M == 2);
out = accumarray(col, row, [size(M,2) 1], @(x) {x});

To double check: 要仔细检查:

>> celldisp(out)

out{1} =

     3
     4

out{2} =

     2
     5

out{3} =

     1
     2
     4

out{4} =

     3

You would use the column locations of where you found the number 2 as the binning parameter and the row locations of where the number 2 is found to group those locations together in the same bin. 您可以将找到2的位置的列位置用作合并参数,将找到2的位置的行位置使用同一位置将这些位置组合在一起。 The default behaviour of accumarray is to sum values that belong to the same bin, but instead of summing values, we group everything together into a single array and the output would thus be a cell array where each index is the desired column location and the cell contents tell you which rows contained the number 2 for the corresponding column. accumarray的默认行为是对属于同一bin的值求和,但不是将值求和,而是将所有内容组合到一个数组中,因此输出将是一个单元格数组,其中每个索引是所需的列位置和该单元格内容告诉您哪些行包含对应列的数字2。

This should also correctly handle the case if there are no values of 2 in a column. 如果一列中没有值2,这也应该正确处理这种情况。 The output for this particular column gives you the empty array. 此特定列的输出将为您提供空数组。 For example, if we had: 例如,如果我们有:

>> M = [1 0 2 0; 0 2 2 1; 2 1 0 1; 2 1 2 0; 0 0 1 1]

M =

     1     0     2     0
     0     2     2     1
     2     1     0     1
     2     1     2     0
     0     0     1     1

Running the code at the beginning of the post, we get: 在文章开头运行代码,我们得到:

>> celldisp(out)

out{1} =

     3
     4

out{2} =

     2

out{3} =

     1
     2
     4

out{4} =

     []

With arrayfun - 使用arrayfun

out = arrayfun(@(n) find(M(:,n)==2),1:size(M,2),'Uni',0)

Verify results with celldisp - 使用celldisp验证结果-

>> celldisp(out)
out{1} =
     3
     4
out{2} =
     2
     5
out{3} =
     1
     2
     4
out{4} =
     3

Yet another approach: 另一种方法:

M = [1 0 2 0; 0 2 2 1; 2 1 0 2; 2 1 2 0; 0 2 1 1]; %// data
v = 2; %// sought value
X = bsxfun(@times, (1:size(M,1)).', M==v); %'
y = nonzeros(X);
z = sum(X~=0, 1);
result = mat2cell(y.', 1, z);

This returns [] for columns that don't contain the sought value. 对于不包含所需值的列,此方法返回[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM