MATLAB: Create a random sequence based on a matrix columns

MATLAB

Hi, given the following matrix
A= [1 3 2 4 5 8 9 11 14;
0 0 0 7 6 12 0 0 0;
0 0 0 0 10 13 0 0 0];
I want to create X random sequences where I associate two random columns of the matrix A, furthermore once I've associated two columns I want to mix randomly the elements in the two sorted columns and create a random sequence in a final vector P. If the number of columns is not even (like this case) there will be one random columns that will remain by itself.
Let's se an example.
For example I randomly combine these columns 1st-3rd, 2nd-4th, 5th-7th , 6th-9th , 8th. that means to mix these values:
2nd – 4th mean : 3, 4 ,7
5th-7th mean : 5, 6, 10 , 9
1st – 3rd mean this values: 1 and 2
6th-9th mean: 8, 12, 13, 14
8th mean: 11
Then I want to create a sequence that follow the order given by the random sort of the column, so first the elements will be 3,4 7 then 5,6,10,9 and so on
But I want to put 3,4,7 in a random order inside the sequence, as well as all the other.
One example clould be :
V = [4 7 3 10 9 6 5 1 2 13 14 12 8 11];
As we can see the order of the elements in the sequence is given by the sorted randomly columns, then the elements in the sorted columns (2by2) are ìnserted with a random order again inside the sequence.
May someone help me with this task?

Best Answer

A= [1 3 2 4 5 8 9 11 14;
0 0 0 7 6 12 0 0 0;
0 0 0 0 10 13 0 0 0];
%first add an extra column of 0s if the number of columns is odd
A = [A, zeros(size(A, 1), mod(-size(A, 2), 2))];
%then pair two columns at random by shuffling the columns and reshaping into twice the height
A = reshape(A(:, randperm(size(A, 2))), size(A, 1)*2, []);
%shuffle each column (pair of original columns
for col = 1:size(A, 2)
A(randperm(size(A, 1)), col) = A(:, col);
end
%then extract the sequence
V = nonzeros(A).'