フィルターのクリア

logical indexing is usually faster than find

105 ビュー (過去 30 日間)
Poonam
Poonam 2013 年 3 月 13 日
コメント済み: Cedric 2014 年 6 月 7 日
j=find(si);
s1=f(j);
logical indexing is usually faster than find,What does this mean,please give solution
  1 件のコメント
Jan
Jan 2013 年 3 月 13 日
Did you search for "logical indexing" in the documentation already? Even searching in the net for "Matlab logical indexing" will find many answers.

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

採用された回答

Cedric
Cedric 2013 年 3 月 13 日
編集済み: Cedric 2013 年 3 月 13 日
There is a little overhead because of the function call and because FIND does a few operations that are unnecessary in most cases where you can use logical indexing.
When you do something like
>> a = [1, 7, 5, 2] ;
>> idx = find(a > 4)
idx =
2 3
>> a(idx) = 0
a =
1 0 0 2
you call the function FIND with an argument that is a vector of logicals that you could directly use for indexing. FIND returns the position on non-false elements in its argument, that you can also use for linear or subscript indexing but with the overhead induced by the "computation" of positions. Using directly the logicals generated by the relational operation (in the present case) avoids the call to FIND, as shown by the last line executed in the code below
>> a = [1, 7, 5, 2] ;
>> a > 4
ans =
0 1 1 0
>> class(ans)
ans =
logical
>> a(a > 4) = 0
a =
1 0 0 2
You could actually easily write a function that roughly does what find does (just to illustrate the principle, assuming 1D arg):
function idx = myFind( x )
allIdx = 1:numel(x) ;
idx = allIdx(x ~= 0) ;
end
Now my experience is (and I call FIND "the infamous FIND" for this reason when I teach MATLAB), that I see people usually using FIND because they don't understand logical indexing, and it sets them up to implementing slow, non-vector, solutions, involving multiple nested FOR loops. For example, you will often see people building statements like
[r,c] = find(A > 4) ; % Get row and column indices.
for ii 1 : numel(r)
for jj = 1 : numel(c)
A(r(ii), c(jj)) = 0 ;
end
end
with e.g. A = rand(1e4), instead of simply doing the following
A(A > 4) = 0 ;
In such case, FIND isn't that slow, but the double loop is!
  2 件のコメント
Chuck
Chuck 2014 年 3 月 24 日
The double for loops don't do the same thing as A(A>4) = 0; The loops set many elements to zero and the loop block is a good example of code not doing what is intended.
Cedric
Cedric 2014 年 6 月 7 日
Errata (thanks Chuck): people often do
[r,c] = find(A > 4) ; % Get row and column indices.
for k = 1 : numel(r)
A(r(k), c(k)) = 0 ;
end

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

その他の回答 (1 件)

ChristianW
ChristianW 2013 年 3 月 13 日
n = 1e6;
r = rand(n,1);
f = randn(n,1)+10;
si = r>0.5;
tic
j = find(si);
s1 = f(j); % with FIND
toc
tic
s2 = f(si); % with logical indexing
toc
all(s1==s2)

カテゴリ

Help Center および File ExchangeImage Processing Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by