如何在每一行中找到非零元素的位置?

时间:2017-10-02 09:23:29

标签: arrays matlab matrix

给定矩阵Access-Control-Allow-Origin: yourhostname:port

A

如何在不使用循环的情况下在A矩阵的每一行中找到非零的位置。预期的结果喜欢

A=[  0     1     1
     1     0     1]

我使用了output=[2 3 1 3] 函数,但它返回了意想不到的结果

find

3 个答案:

答案 0 :(得分:5)

方法#1

使用find获取展平数组中的列索引,然后重新整形 -

[c,~] = find(A.')
out = reshape(c,[],size(A,1)).'

示例运行 -

>> A
A =
     0     1     1
     1     0     1
     1     1     0
>> [c,~] = find(A.');
>> reshape(c,[],size(A,1)).'
ans =
     2     3
     1     3
     1     2

方法#2

我们可以通过一些排序来避免输入数组的转置 -

[r,c]  = find(A);
[~,idx] = sort(r);
out = reshape(c(idx),[],size(A,1)).'

基准

我们将平铺行以形成更大的输入矩阵并测试所提出的方法。

基准代码 -

% Setup input array
A0 = [ 0 1 1;1 0 1;1,1,0;1,0,1];
N = 10000000; % number of times to tile the input rows to create bigger one
A = A0(randi(size(A0,1),N,1),:);

disp('----------------------------------- App#1')
tic,
[c,~] = find(A.');
out = reshape(c,[],size(A,1)).';
toc
clear c out

disp('----------------------------------- App#2')
tic,
[r,c]  = find(A);
[~,idx] = sort(r);
out = reshape(c(idx),[],size(A,1)).';
toc
clear r c idx out

disp('----------------------------------- Wolfie soln')
tic,
[row, col] = find(A);
[~, idx] = sort(row);
out = [col(idx(1:2:end)), col(idx(2:2:end))];
toc

计时 -

----------------------------------- App#1
Elapsed time is 0.273673 seconds.
----------------------------------- App#2
Elapsed time is 0.973667 seconds.
----------------------------------- Wolfie soln
Elapsed time is 0.979726 seconds.

很难在App#2和@ Wolfie's soln之间做出选择,因为时间似乎相当,但第一个看起来非常有效。

答案 1 :(得分:2)

您只需使用findsort即可实现此目的。我将使用与Divakar的连续性相同的测试示例。

% Set up some matrix with only 2 non-zero elements per row
A = [ 0     1     1
      1     0     1
      1     1     0 ];

% Find rows/columns of non-zero elements
[row, col] = find(A);
% Get sort indices, should be two of each row value (for two non-zero elems)
[~, idx] = sort(row);
% Concatenate horizontally the first and second column indices from each row
out = [col(idx(1:2:end)), col(idx(2:2:end))];

>> disp(out)
>> [2     3
    1     3
    1     2]

与Divakar的解决方案相比,两种方法都执行相同的sort操作,但此方法并不需要任何转置或重塑。有关基准测试,请参阅that answer

答案 2 :(得分:1)

如果只有3列,您可以使用此方法:

x = [1 2;1 3;2 3];
output = x((A *(0:2).').',:);

@Divakar八度音阶基准测试的结果:

----------------------------------- App#1
Elapsed time is 0.813956 seconds.
----------------------------------- App#2
Elapsed time is 0.9617 seconds.
----------------------------------- Wolfie soln
Elapsed time is 1.49294 seconds.
----------------------------------- rahnema1 soln
Elapsed time is 0.221258 seconds.

我们可以将其推广到其他列大小:

x=nchoosek(1:size(A,2),2);
output = x((A *(0:size(A,2)-1).').',:);

[a b]=find(tril(true(size(A,2)),-1));
idx = (A *(0:size(A,2)-1).').';
output=[b(idx) a(idx)];