Matlab code, please complete the required code below (in bold font): function to
ID: 3582723 • Letter: M
Question
Matlab code, please complete the required code below (in bold font):
function total = sudoku(x)
% Make sure you set the number of variables to 16 in the GA Tool
% And also select population type = "Double Vector"
% first, initialize the fitness to zero
total = 0;
% eliminate fractions from the chromosome ( converts to int )
x = round(x);
% increase fitness if there's a gene not in the range between 1 to 4
for i=1:16
if x(i) > 4 || x(i) < 1
total = total + 1 ;
end
end
% reshape the chromosome as 2D (4*4)
x=reshape(x,4,4);
% set the sudoku puzzle
x(1,1) = 1;
x(1,4) = 2;
x(2,3) = 1;
x(3,2) = 3;
x(4,1) = 4;
x(4,4) = 3;
% calculate chromosome's fitness
% (YOUR_CODE_HERE) (THE_ASSIGNMENT) (JUST A Nested Loop)
% prints the solution
if total == 0
clc
x
end
end
Explanation / Answer
function total = sudoku(x)
% Make sure you set the number of variables to 16 in the GA Tool
% And also select population type = "Double Vector"
% first, initialize the fitness to zero
total = 0;
% eliminate fractions from the chromosome ( converts to int )
x = round(x);
% increase fitness if there's a gene not in the range between 1 to 4
for i=1:16
if x(i) > 4 || x(i) < 1
total = total + 1 ;
end
end
% reshape the chromosome as 2D (4*4)
x=reshape(x,4,4);
% set the sudoku puzzle
x(1,1) = 1;
x(1,4) = 2;
x(2,3) = 1;
x(3,2) = 3;
x(4,1) = 4;
x(4,4) = 3;
% calculate chromosome's fitness
% (YOUR_CODE_HERE) (THE_ASSIGNMENT) (JUST A Nested Loop)
for i=1:16 %outer loop of the nested loop
for i=1:16 %inner loop of the nested loop
total = total + x(1,1); %calculate chromosome's fitness
end
end
% prints the solution
if total == 0
clc
x
end
end