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

2 ビュー (過去 30 日間)
Austin
Austin 2014 年 2 月 22 日
編集済み: Austin 2014 年 2 月 22 日
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

採用された回答

Mischa Kim
Mischa Kim 2014 年 2 月 22 日
編集済み: Mischa Kim 2014 年 2 月 22 日
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 件のコメント
Austin
Austin 2014 年 2 月 22 日
編集済み: Austin 2014 年 2 月 22 日
It works,Thanks Alot bro!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by