How to optimize the following function

Hello everyone:)
It's somewhat a crosspost from stackoverflow http://stackoverflow.com/questions/21146693/sensibility-of-converting-matlab-program-in-java-to-improve-performance. We try to develop a genetic algorithm approach to find a solution to the sudoku game. We've noticed that the code takes too long to calculate one generation and after profiling it found out that the following function takes most of the time, the hotspot (as expected) is the call to
intersect(s,board(i,:))
I think it's because it runs in a loop. Is there a non-loop alternative to compute the difference. Basically we want to find out how many duplicates each row have (in the range of possible values from 1 to 9). Here is the code:
%%%used this code to make a post on stackoverflow
%http://stackoverflow.com/questions/21146693/sensibility-of-converting-matlab-program-in-java-to-improve-performance
function [fitness, finished,d, threshold]=fitness(population_, n)
finished=false;
threshold=false;
V=ones(n,1);
d=zeros(size(population_,2),1);
s=[1:1:n];
for z=1:size(population_,2)
board=population_{z};
t=0;
l=0;
for i=1:n
l=l+n-length(intersect(s,board(:,i)'));
t=t+n-length(intersect(s,board(i,:)));
end
k=sum(abs(board*V-t));
f=t+l+k/50;
if t==2 &&l==2
threshold=true;
end
if f==0
finished=true;
else
fitness(z)=1/f;
d(z)=f;
end
end
end
Thank you loads

 採用された回答

Walter Roberson
Walter Roberson 2014 年 1 月 17 日

0 投票

histc(V, 1:9) > 1
you can then any() that if you just want to know if there are duplicates at all, or you can sum() it if you want to know how many distinct digits have duplicates.
Or you could experiment with the timing of sparse(V, 1, 1) > 1 and of accumarray(V(:), 1) > 1

2 件のコメント

Sean de Wolski
Sean de Wolski 2014 年 1 月 17 日
Also ismember is significantly faster than intersect
den
den 2014 年 1 月 17 日
Oh, thanks a lot. we used histc, it's so much faster

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSudoku についてさらに検索

質問済み:

den
2014 年 1 月 17 日

コメント済み:

den
2014 年 1 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by