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

matrix minimum column

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

Best Answer

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