MATLAB: How to do crossover between two matrices.

matricesmatrixmatrix arraymatrix manipulation

Suppose we have two matrices A and B. Now we randomly select the number of a rows which corresponds to a non-zero row and exchanges the corresponding rows between two matrices.
For example
A =
[0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0]
B =[0 0 0 0 1 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0]
Now suppose randomly we selected row number 1 and 3. so we exchange these rows between matrices A and B and the answer matrices are
C =
[0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0]
D =[0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0]

Best Answer

ii = [1,3]
E = cat(3,A,B);
E(ii,:,:) = E(ii,:,end:-1:1);
CC = num2cell(E,[1,2]);
[C,D] = CC{:};