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

2 vues (au cours des 30 derniers jours)
Austin
Austin le 22 Fév 2014
Modifié(e) : Austin le 22 Fév 2014
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

Réponse acceptée

Mischa Kim
Mischa Kim le 22 Fév 2014
Modifié(e) : Mischa Kim le 22 Fév 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);
  1 commentaire
Austin
Austin le 22 Fév 2014
Modifié(e) : Austin le 22 Fév 2014
It works,Thanks Alot bro!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by