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]
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)).'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With