Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find position of nonzero elements in each row?

Given a matrix A is

A=[  0     1     1
     1     0     1]

How can I find the location of nonzeros in each row of the A matrix, without using loop. The expected result likes

output=[2 3
        1 3]

I was used find function but it return the unexpected result likes

 output=[2
         3
         5
         6]
like image 518
Jame Avatar asked Dec 20 '25 03:12

Jame


1 Answers

Approach #1

Use find to get the column indices in a flattened array and then reshape -

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

Sample run -

>> 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

Approach #2

We could avoid the transposing of the input array, with some sorting -

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

Benchmarking

We will tile the rows to form a bigger input matrix and test out the proposed methods.

Benchmarking code -

% 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

Timings -

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

It's hard to choose between App#2 and @Wolfie's soln as the timings seem comparable, but the first one seems quite efficient.

like image 135
Divakar Avatar answered Dec 23 '25 03:12

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!