## How to vectorize a find

Matlab2010

### Matlab2010 (view profile)

さんによって質問されました 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

Matlab2010

### Matlab2010 (view profile)

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
for z = 1 : length(trades)
for kk = 1:length(p)
lastTimeValue(z) = kk-1;
break;
end
end
end
%METHOD 3
for z = 1 : length(trades)
temp = cumsum(I(1:z));
lastTimeValue_TEST(z) = temp(end);
end

サインイン to comment.

## 3 件の回答

2012 年 12 月 11 日

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.

Matlab2010

### Matlab2010 (view profile)

2012 年 12 月 11 日
find.m isn't vectorized to my knowledge. x==1 is.
I have a large dataset, which results in a large number of calls. In my experince it pays to try and replace some of the inbuilt functions with vectorized form.
There is a blog post by loren on speeding up find according to google but the URL is broken.

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

2012 年 12 月 11 日
Also, see my edit above for a faster method if you have a binary array.

サインイン to comment.

### Sean de Wolski (view profile)

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.

#### 0 件のコメント

サインイン to comment.

2012 年 12 月 11 日

### Mark Whirdy (view profile)

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

#### 0 件のコメント

サインイン to comment.

Translated by