Filter löschen
Filter löschen

Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

Optimize the FOR loop

1 Ansicht (letzte 30 Tage)
Sam
Sam am 28 Jun. 2012
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
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 Kommentare
Ryan
Ryan am 28 Jun. 2012
Bearbeitet: Ryan am 28 Jun. 2012
To clarify: For each value in 'x', you're trying to locate the position of the first value in 'y' that is greater than the value in 'x' and then return that position in a vector 'z'?
Sam
Sam am 28 Jun. 2012
yes

Antworten (2)

Sean de Wolski
Sean de Wolski am 28 Jun. 2012
Bearbeitet: Sean de Wolski am 28 Jun. 2012
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 Kommentare
Tom
Tom am 28 Jun. 2012
I just compared arrayfun and bsxfun, the latter is a whole order of magnitude faster.
Ryan
Ryan am 28 Jun. 2012
Thank you Sean and Tom!

Tom
Tom am 28 Jun. 2012
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 Kommentar
Tom
Tom am 28 Jun. 2012
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.

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by