Create a random sequence based on a matrix columns

2 次查看(过去 30 天)
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?

采纳的回答

Guillaume
Guillaume 2019-10-3
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).'
  2 个评论
luca
luca 2019-10-3
How can I run this for collect X different vector V. with a for cycle is the most clever way?
for i= 1:X
...
end
Or there is a more clever way?
Guillaume
Guillaume 2019-10-3
编辑:Guillaume 2019-10-3
Using matlab's function there's no other way than a loop indeed.
If you download jan's Shuffle, then this will be a lot more efficient
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];
X = 10;
%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))];
%shuffle columns X times and reshape into 3D matrix. Each page is a shuffle of the columns of A
cols = Shuffle(repmat((1:size(A, 2))', 1, X), 1)
B = reshape(A(:, cols), size(A, 1)*2, [], X)
%shuffle rows extract non zeros
V = reshape(nonzeros(Shuffle(B, 1)), nnz(A), []).'

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by