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

Jam*_*ame 2 arrays matlab matrix

鉴于矩阵A

A=[  0     1     1
     1     0     1]
Run Code Online (Sandbox Code Playgroud)

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

output=[2 3
        1 3]
Run Code Online (Sandbox Code Playgroud)

我用过find函数但是它返回了意想不到的结果

 output=[2
         3
         5
         6]
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 5

方法#1

用于find在扁平数组中获取列索引,然后重新整形 -

[c,~] = find(A.')
out = reshape(c,[],size(A,1)).'
Run Code Online (Sandbox Code Playgroud)

样品运行 -

>> 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
Run Code Online (Sandbox Code Playgroud)

方法#2

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

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

标杆

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

基准代码 -

% 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
Run Code Online (Sandbox Code Playgroud)

计时 -

----------------------------------- App#1
Elapsed time is 0.273673 seconds.
----------------------------------- App#2
Elapsed time is 0.973667 seconds.
----------------------------------- Wolfie soln
Elapsed time is 0.979726 seconds.
Run Code Online (Sandbox Code Playgroud)

很难在App#2@ Wolfie的解决之间进行选择,因为时间似乎可以比较,但第一个看起来非常有效.