How to vectorize the find function?

1 回表示 (過去 30 日間)
Bernard Küsel
Bernard Küsel 2011 年 5 月 13 日
This is my code:
for i=1:size(Z,3)
indmax(i)=find(abs(Z(1,:,i))>z90(1,1,i),1);
indmin(i)=find(abs(Z(1,:,i))>z10(1,1,i),1);
end
trise(:,1)=(t(indmax)-t(indmin));
The variable Z is normally 3 or 6 rows, many columns and 5-10 pages. Something like:
size(Z)= 6 1920 8
The variables z10 and z90 have the same number of rows and pages as Z and 1 column. Something like:
size(z10)=size(z90)=6 1 8
I would actually need to repeat this code 6 more times (1 for each row).
Is there a way to vectorize this?

採用された回答

Sean de Wolski
Sean de Wolski 2011 年 5 月 13 日
%small sample because you only looped over first row
Z = rand(1,5,8)*2.5;
z90 = rand(1,1,8);
z10 = rand(1,1,8);
%Your way
for i=1:size(Z,3)
indmax(i)=find(abs(Z(1,:,i))>z90(1,1,i),1);
indmin(i)=find(abs(Z(1,:,i))>z10(1,1,i),1);
end
%Vectozed way:
[jk, indmx] = max(bsxfun(@gt,abs(Z),z90),[],2);
[jk, indmn] = max(bsxfun(@gt,abs(Z),z10),[],2);
indmx = squeeze(indmx);
indmn = squeeze(indmin);
isequal(indmin,indmn)
isequal(indmax,indmx.') %transpose rowvec
This method is extended to the full size, though just looping over the six rows is probably just as easy/fast. I.e. loop 1:6, extract trise on each iteration.
  6 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 5 月 13 日
^^^^Jealous.
Bernard Küsel
Bernard Küsel 2011 年 5 月 16 日
Thanks for the help!

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

その他の回答 (1 件)

Doug Hull
Doug Hull 2011 年 5 月 13 日
Why vectorize?
Just add another for loop for the rows.
  4 件のコメント
Doug Hull
Doug Hull 2011 年 5 月 13 日
Your question is then about speeding up the code, not about vectorizing?
Bernard Küsel
Bernard Küsel 2011 年 5 月 16 日
Yeah, sorry about that.. It's just that vectorizing usually speeds up the code.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by