How to vectorize a find

조회 수: 10 (최근 30일)
Matlab2010
Matlab2010 2012년 12월 11일
x = zeros(1000,1);
x(76) = 1;
x(100) = 1;
x(200) = 1;
I can do:
first = find(x ==1, 1, 'first'); %the answer =76
but this is slow. I would like to speed this up. How? thanks
  댓글 수: 1
Matlab2010
Matlab2010 2013년 1월 15일
편집: Matlab2010 2013년 1월 15일
just going to put up some code which might help others looking for v fast finds in future:
Method 3 is incredibly fast (credit to Matt J!)
%METHOD 1
lastTimeValue_SLOW = arrayfun(@(x,y) find(data(x:end,2) <= y, 1, 'last'), trades, tradeTimePlusDt); %works but v slow!
%METHOD 2
lastTimeValue = NaN(length(trades),1);
for z = 1 : length(trades)
p=data(trades(z):end,2);
for kk = 1:length(p)
if(tradeTimePlusDt(z) <= p(kk))
lastTimeValue(z) = kk-1;
break;
end
end
end
%METHOD 3
%http://www.mathworks.co.uk/matlabcentral/newsreader/view_thread/304895
lastTimeValue_TEST = NaN(length(trades),1);
for z = 1 : length(trades)
I = histc(data(trades(z):end,2),[-inf;tradeTimePlusDt] );
temp = cumsum(I(1:z));
lastTimeValue_TEST(z) = temp(end);
end

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

채택된 답변

Matt Fig
Matt Fig 2012년 12월 11일
편집: Matt Fig 2012년 12월 11일
The last statement you show is vectorized, so the question is ill-posed. I think what you are asking for is a way to speed up the process.
Also, just how fast do you think it should be??
x = zeros(1000,1);
x(76) = 1;
x(100) = 1;
x(200) = 1;
tic,first = find(x ==1, 1, 'first');toc
Elapsed time is 0.000023 seconds. % That is slow???
.
.
.
EDIT
I did find a way to do it faster, but it will only work if you have a binary matrix as in your example. You can avoid the comparison as it is not necessary.
tic,first = find(x);first = first(1);toc
Elapsed time is 0.000012 seconds.
  댓글 수: 3
Matt Fig
Matt Fig 2012년 12월 11일
편집: Matt Fig 2012년 12월 11일
There is no find.m in MATLAB.
which find
built-in (C:\Program Files\MATLAB\R2011b\toolbox\matlab\elmat\@logical\find) % logical method
Matt Fig
Matt Fig 2012년 12월 11일
Also, see my edit above for a faster method if you have a binary array.

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

추가 답변 (2개)

Sean de Wolski
Sean de Wolski 2012년 12월 11일
If you only have zeros and ones and you are positive there is atleast one one, then you can use the second output from max().
[~,first] = max(x);
I don't know if this will be faster or not.

Mark Whirdy
Mark Whirdy 2012년 12월 11일
편집: Mark Whirdy 2012년 12월 11일
a temporary vector of row numbers, then use your vector-of-interest & a logicsl statement to index this row-number vector
a =[1:size(x,1)]'; % row numbers
b=a(x==1); % logical indexing the populated rows
b(1) % first instance

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by