parent1= 0 0 0 0 1 0 0 1 and parent2=0 0 0 0 1 1 0 0 and i have another parent 1 to 50 element and i want swap 7 and 8th raw
2 views (last 30 days)
Show older comments
Pratik Anandpara
on 13 Dec 2016
Edited: Pratik Anandpara
on 14 Dec 2016
parent 1 :0 0 0 0 1 0 0 1
parent 2: 0 0 0 0 1 1 0 0
swap 7 & 8 element of both1 and create new one
child 1: 0 0 0 0 1 0 0 0
child 2: 0 0 0 0 1 1 0 1
parent 1 & 2 create child 1& 2 same like 3 and 4....5 & 6...done further process in for loop for 1 to 50 all parent and child are in 8 bit digit but here consider as 1*8 matrix or array of 8 entry
child2=parent(1,:);
child2(swapping)=parent(4,:)(swapping);
i tried this but here 'parent(4,:)(swapping)' part create error
0 Comments
Accepted Answer
Guillaume
on 14 Dec 2016
Don't number variables. It's going to give you problems later on.
You can't chain indexing. What you mean by
p(2, :)(end)
is actually
p(2, end)
So, for your example:
parent = [0 0 0 0 1 0 0 1;
0 0 0 0 1 1 0 0]
child = parent;
swappedcolumns = [7 8];
child([1 2], swappedcolumns) = child([2 1], swappedcolumns)
Notice that the order of the rows has been reversed in the assignment in order to swap the swappedcolumns of row 1 and 2.
One way to swap all even and odd rows:
parent = randi([0 1], 50, 8) %demo data
swappedcolumns = [7 8];
child = parent;
swapoddeven = reshape([2:2:size(parent, 1); 1:2:size(parent, 1)], 1, []); %create vector of [2 1 4 3 6 5 ...]
child(swapoddeven, swappedcolumns) = child(1:size(parent, 1), swappedcolumns)
No loop needed
5 Comments
Guillaume
on 14 Dec 2016
Your comment is completely unreadable. Please, get rid of all these blank lines between each line of code and use the {}Code button to format your code instead.
It does not make people to want to help you when you accept their answer and then unaccept it when it does not answer a completely different question that you ask in the comments.
I recommend that you reaccept the answer and ask your new question in a completely new post, linking this question and the one where you must have had the first part of your code.
More Answers (1)
KSSV
on 14 Dec 2016
p1 = [0 0 0 0 1 0 0 1] ;
p2= [0 0 0 0 1 1 0 0] ;
c1 = p1 ;
c2 = p2 ;
c1(end) = p2(end) ;
c2(end) = p1(end) ;
See Also
Categories
Find more on Genetic Algorithm in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!