low speed of 'ismember' function

3 次查看(过去 30 天)
Ehsan
Ehsan 2014-8-29
评论: Ehsan 2014-8-29
hi. in my code there is a for loop like the following:
for i=1:n
N=find(~ismember(Vector1,Vector2))
do something...
end
This loop is repeated several thousand times. 'ismember' function is very slow. So that most of the runtime for 'ismember' function lost. Is there any alternative to this?

回答(3 个)

Johan Löfberg
Johan Löfberg 2014-8-29
If data is sorted, using ismembc could be a quick fix.
  2 个评论
Ehsan
Ehsan 2014-8-29
No. This loop used for programming the Traveling Salesman Problem. this vectors is not sorted and can't be like that.
Johan Löfberg
Johan Löfberg 2014-8-29
Then I would scratch ismember and do sort+ismembc (ismember contains a lot of overhead. look into it and you will see that it basically does sort+ismembc once all data is checked etc)

请先登录,再进行评论。


David Sanchez
David Sanchez 2014-8-29
Depending on your data, you might try to code your own function avoiding some conditions and calls to sub-functions within the ismember function.
You can take a look at ismember code with:
type ismember
and try to make it easier.
  3 个评论
José-Luis
José-Luis 2014-8-29
The way you use ismember() seems to be inefficient. You are going to be processing similar things over and over. You could instead loop through the variable of interest, do an exhaustive search, save that somewhere and then %do something based on those results.
Ehsan
Ehsan 2014-8-29
I just do not understand. What is your suggestion? Please change the code according to your suggestion.

请先登录,再进行评论。


Titus Edelhofer
Titus Edelhofer 2014-8-29
Hi,
does "Vector1" and "Vector2" changes in every iteration? Often you see something like
for i=1:n
v = ismember(x(i), y);
% do something
end
which can be changed to
vAll = ismember(x, y);
for i=1:n
% now do something with vAll(i)
end
Titus
  1 个评论
Ehsan
Ehsan 2014-8-29
this is my code:
for k=1:nAnt
ant(k).Tour=randi([1,nCity],1,1);
end
for i=2:nCity
for k=1:nAnt
N=find(~ismember(1:nCity,ant(k).Tour));
% do somthing
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by