Find the first column in a matrix that contains at least 1 non zero..

3 views (last 30 days)
Hi,im trying to find the first column in a matrix that contain at least 1 non zero. then the function Findfirst should return me with the column number that refers to the leftmost column in a matrix that contains at least a non zero element. below is my code but i dont seem to get the right results can anybody help me in identifying my error?
function [p] = Findfirst(A,currentRow) [m n]=size(A); p=1; for i=currentRow:m; for j=1:n; if A(i,j)~=0 p=i; if p<n p=n else p=n+1; end
end end end

Accepted Answer

Mischa Kim
Mischa Kim on 22 Feb 2014
Edited: Mischa Kim on 22 Feb 2014
Austin, here you go:
function [p] = Findfirst(A,currentRow)
[m n]=size(A);
p=n;
for i=currentRow:m
for j=1:n
if A(i,j)~=0
p=j; % you wanted to get the col index, right?
break; % break out once you have your solution
end
end
end
end
A bit more compact...
function [p] = Findfirst(A)
p = [];
for ii = 1:length(A(1,:))
if ~isempty(find(A(:,ii)))
p = ii;
break;
end
end
end
For small-size matrices you could also
[r c] = find(A);
p = min(c);

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!