Help with vectorizing find command

Hi,
I'm working on some code for roulette wheel selection and have some problems vectorizing the last two lines of this section.
parents = zeros(1, 2);
indexes = [12; 32; 35; 36; 47];
cs = [0.21; 0.41; 0.58; 0.79; 1.00];
r = rand(1, 2);
parents(1) = indexes(find(r(1) < cs, 1));
parents(2) = indexes(find(r(2) < cs, 1));
I already tried the following, but it resulted in an error because the dimensions of r and cs don't match:
parents = indexes(find(r < cs, 1));
I know that vectorizing this particular example won't make much of a difference in terms of speed, but it will help me get better in terms of programming with Matlab. So any help would be appreciated..

답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 7월 29일
편집: Azzi Abdelmalek 2013년 7월 29일

1 개 추천

parents =arrayfun(@(x) indexes(find(x < cs,1)),r);
But the for loop is 15 faster
Edit
parents=zeros(1,numel(r)); % Pre-allocate
for k=1:numel(r)
parents(k)=indexes(find(r(k)< cs,1));
end

댓글 수: 3

dave
dave 2013년 7월 29일
Thanks for your help, Azzi. If the for loop is so much faster, I guess I'm gonna stick with it and forget about vectorizing these lines.
Azzi Abdelmalek
Azzi Abdelmalek 2013년 7월 29일
편집: Azzi Abdelmalek 2013년 7월 29일
This does not mean there is no better way. In the above code I forget to Pre-allocate. Look at Edit
Speed test for a code in the loop (1000 times)
Elapsed time is 0.312394 seconds. Dpb's answer
Elapsed time is 0.009241 seconds. Azzi for loop answer
Elapsed time is 0.181920 seconds. Azzi's arrayfun answer

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

dpb
dpb 2013년 7월 29일

0 개 추천

parents=accumarray([1:2]',r,[],@(x) indexes(find(x<cs,1)));

댓글 수: 2

dave
dave 2013년 7월 29일
Thanks dpb...nice one!
dpb
dpb 2013년 7월 29일
Didn't time it...that wasn't part of the request... :)

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2013년 7월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by