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

 Respuesta aceptada

Walter Roberson
Walter Roberson el 17 de En. de 2014
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 comentarios

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Sudoku en Centro de ayuda y File Exchange.

Preguntada:

den
el 17 de En. de 2014

Comentada:

den
el 17 de En. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by