Optimize the FOR loop
정보
이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.
이전 댓글 표시
I am learning to optimize the following nested FOR loop, any comments are appreciated,
x=[537 558 583 606 631 655 666 700 722 799 823 847];
y=[48 216 384 552 720 888 1056];
z = zeros(1,numel(x));
for j = 1:numel(x)
for i = 1:numel(y)
if(x(j) <= y(i) )
z(j) = i;
break;
end
end
end
%ans
%z = [4 5 5 5 5 5 5 5 6 6 6 6]
답변 (2개)
Sean de Wolski
2012년 6월 28일
편집: Sean de Wolski
2012년 6월 28일
If you can guarantee that the is at least one occurence of x(:) <y (:) then this will work:
x=[537 558 583 606 631 655 666 700 722 799 823 847];
y=[48 216 384 552 720 888 1056];
[~,z] = max(bsxfun(@le,x,y'),[],1)
댓글 수: 4
Ryan
2012년 6월 28일
I have never used arrayfun or cellfun or bsxfun before and am trying to understand them and have two questions about this solution:
- Why do you need to transpose y?
- Is the ~ used to not waste space saving the max values because all you needed was the indices?
Sean de Wolski
2012년 6월 28일
Hi Ryan,
For your first question,
bsxfun: please see my answer from a long time ago here: http://www.mathworks.com/matlabcentral/answers/16257#answer_22019
cellfun: Apply some function each cell. Can be useful sometimes for simple calculations, e.g: How many elements in each cell?
cellfun(@numel,C);
For any complicated function, just us e a for-loop, it'll likely be faster.
arrayfun: personal opinion is that it is confusing and slow and should be avoided.
Second question: exactly!
Tom
2012년 6월 28일
I just compared arrayfun and bsxfun, the latter is a whole order of magnitude faster.
Ryan
2012년 6월 28일
Thank you Sean and Tom!
Tom
2012년 6월 28일
It seems what you're trying to is find the first instance of each value of x being less than each value of y. You can do this in using arrayfun:
arrayfun(@(n) find(n<y,1),x)
the first argument is an anonymous function. For each value in x, the find function is used to find the first instance of that x value being less than the y vector.
댓글 수: 1
Tom
2012년 6월 28일
Seeing what Sean said, this way also only works if there is an occurrence of for all of them- if there isn't then 'UniformOutput' has to be set to false, which means the output will be a cell array.
이 질문은 마감되었습니다.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!