2016-03-05 390 views
0

我需要通過採用任意兩個使用單點交叉的矩陣來進行交叉。在Matlab中的代碼是什麼?如何在matlab中的兩個矩陣之間進行單點交叉

n=input('no.of ROWS AND COLUMNS'); 
sm_mat = eye(n); 
for i=1:n 
    temp = randperm(n); 
    fprintf('Initial Population %d\n',i) 
    eval(['sm_mat_', num2str(i) '=sm_mat(:,temp)']); 
end 
+0

我需要採取任何兩個矩陣,想越過..上面創建在不同的地方1與每行一個1的。 –

+0

該問題的任何其他信息(例如您發佈的代碼)都應添加到問題本身中。您可以使用問題選項卡下方的[編輯]鏈接(或我的評論中的兩個[編輯]鏈接)。 – BSMP

+0

請使用正確的代碼格式(即大括號)編輯您的問題。此外,澄清(以一個例子將是可愛的)沿着哪個維度交叉應該被執行。 – Alessiox

回答

0

如果我正確理解您的問題是什麼,您可以輕鬆地手動執行單點交叉。因此,您需要創建可能的父母,隨機選擇其中的兩個,然後在他們的行之間執行交叉以創建新的個人(孩子)。

而不是爲每個(候選人)家長創建不同的變量(這將使這兩個父母的隨機選擇難以置信地難)我建議你創建一個單元格陣列與n單元格,其中第i個單元格將包含我 - 矩陣(候選父)。

n=input('no.of ROWS AND COLUMNS'); 
sm_mat = eye(n); 
for i=1:n 
    temp = randperm(n); 
%  fprintf('Initial Population %d\n',i) 
%  eval(['sm_mat_', num2str(i) '=sm_mat(:,temp)']); 
    InitialPopCell{i}=sm_mat(:,temp); 
end 

InitialPopCell將成爲我們的細胞陣列。
現在您需要隨機選擇兩個父母:要做到這一點,您可以隨意選擇兩個不同的細胞。

i=0; j=0; 
while i==j 
    i=randi(n); 
    j=randi(n); 
end 

以這種方式,我們選擇兩個索引(ij)考慮到它們必須在範圍[1:n]和它們必須是彼此不同的。
現在我們可以選擇兩個父母:

ParentA=InitialPopCell{i}; 
ParentB=InitialPopCell{j}; 
Child=[]; 

我們也初始化爲空Child(即新個體)矩陣。
現在,終於,讓我們進行交叉:

for i=1:size(ParentA,1) 
    % select random integer between 1 and the number of chromosomes 
    % this will be the crossover point 
    XOverPoint=randi(size(ParentA,2)); 

    % create new individual by concatenating Parent A and B taking into 
    % account the crossover point 
    Child(i,:)=[ParentA(i,1:XOverPoint) ParentB(i,XOverPoint+1:end)]; 
end