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

2 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Mischa Kim
Mischa Kim el 22 de Feb. de 2014
Editada: Mischa Kim el 22 de Feb. de 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);

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by