# Find first non-zero column of a matrix

67 views (last 30 days)
Rodrigo Pereira on 27 Aug 2016
Edited: dpb on 27 Aug 2016
How do I, given a matriz A, tell MATLAB to find the index of the leftmost non-zero column of said matrix?

dpb on 27 Aug 2016
Edited: dpb on 27 Aug 2016
>> A=[zeros(5) randn(5)]; A=A(:,randperm(10)); % sample dataset
A =
-0.7440 1.0223 0 -0.7062 0 0.1257 0 1.2390 0 0
-0.3744 -1.4192 0 -1.0207 0 0.6963 0 0.8987 0 0
0.4241 2.5467 0 1.1340 0 1.7395 0 -1.1501 0 0
0.1141 -0.3580 0 0.0385 0 0.6654 0 -0.2642 0 0
-0.5111 0.4013 0 0.2309 0 0.6875 0 -1.6252 0 0
>> find(any(A),1) % first column nonzero
ans =
1
>>
That one seems too easy; let's try again...
>> A=A(:,randperm(10));
A =
0 -0.7440 0 0 1.0223 1.2390 0 0 0.1257 -0.7062
0 -0.3744 0 0 -1.4192 0.8987 0 0 0.6963 -1.0207
0 0.4241 0 0 2.5467 -1.1501 0 0 1.7395 1.1340
0 0.1141 0 0 -0.3580 -0.2642 0 0 0.6654 0.0385
0 -0.5111 0 0 0.4013 -1.6252 0 0 0.6875 0.2309
>> find(any(A),1)
ans =
2
>>
OK, that's more difficult and illustrates it does work as expected...

Azzi Abdelmalek on 27 Aug 2016
A=randi([0 2],20,8)
[~,out]=max(sum(logical(A)))

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by