Looking for a way faster than find?

조회 수: 13 (최근 30일)
Benson Gou
Benson Gou 2021년 6월 21일
댓글: Joseph Cheng 2021년 6월 21일
Dear All,
I have an array A. I want to find out the index of those "1" entries in the array A.
For example, A = [1 2 5 1 3 2 8 10 1]. I want to find out the indecis of those "1" in A.
I used logical indexing to find the location but cannot get the indecis.
a = A == 1;
a = [1 0 0 1 0 0 0 0 1].
How can I find the indecis of nonzero in a?
Thanks.
Benson

채택된 답변

Joseph Cheng
Joseph Cheng 2021년 6월 21일
편집: Joseph Cheng 2021년 6월 21일
without doing some testing to actually test if its faster you can use the found 1's in a to only select a list of indexes
A = [1 2 5 1 3 2 8 10 1];
a = A==1
a = 1×9 logical array
1 0 0 1 0 0 0 0 1
inds = [1:numel(A)];
inds(a)
ans = 1×3
1 4 9
  댓글 수: 2
Benson Gou
Benson Gou 2021년 6월 21일
Hi, Joseph,
Thanks for your promt reply.
I compared the speed between find and your code. I found the following:
tic
a = A == 1;
inds = 1:numel(a);
c = inds(a)
toc
Elapsed time is 0.004136 seconds.
tic;
find(A==1);
toc
Elapsed time is 0.000365 seconds.
Using find is faster than the above code.
Joseph Cheng
Joseph Cheng 2021년 6월 21일
but it did answer your i "I used logical indexing to find the location but cannot get the indecis... How can I find the indecis of nonzero in a?"

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by