Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

why setdiff have time longer than for ?

Asked by huda nawaf on 12 May 2013

*hi,

Itried to make my code be faster , so i used setdiff instead of a part in my code

I used:*

                  v=(1:18);
                   buf=setdiff(v,unique_x);
                  relevant_item(ttt(i),1:length(buf))=buf;

*instead of *

                  for v=1:18
                    b2=find(unique_x==v);
                   if isempty(b2)
                       relevant_item(ttt(i),h)=v;
                       h=h+1;
                   end
               end

*why the running time of this part is less than of setdiff?

thanks*

0 Comments

huda nawaf

Tags

Products

No products are associated with this question.

1 Answer

Answer by Walter Roberson on 12 May 2013
Accepted answer

setdiff() essentially has to sort each time -- or at least to check if the set is ordered.

Are the unique_x restricted to being in the allowed range for v, 1:18 ? If so, then how about

buf = 1:10;
buf(unique_x) = [];
relevant_item(ttt(i),1:length(buf))=buf;

3 Comments

huda nawaf on 12 May 2013

thanks ,yes it is best in terms of time

huda nawaf on 15 May 2013

Walter, if buf =[ 3 49 10 4 7 20];

I mean not 1:18, can find way to run the above code neither use setdiff , nor for?

thanks

Jan Simon on 15 May 2013

@huda: Look into the code of setdiff. You find the relevant part in the fast MEX function ismembc2, which expects pre-sorted data. So sort your data explicitly, call this function and use the replied indices. Note that ismembc2 is not documented, but you find enough information about it in the net.

Walter Roberson

Contact us