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 Exchange에서 Sudoku에 대해 자세히 알아보기

질문:

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