How to suffle rows of specific rows from a matrix

2 次查看(过去 30 天)
Hello I have a matrix with 2 columns and 120 rows. the first columns has numbers 2-6 and the second one is 0 and 1 like the following
[2 1]
[3 0]
[2 0]
[4 0]
[6 1]
[2 1] etc.
I want to shuffle randomly the second column to produce a new column. In this new column I want to shuffle the rows of the second column, that their first column is between 2 and 5. Also shuffle the rows on the second column that the first column is 6 between them. More specifically if I have a sequence in the following way
[2 1] [3 0] [6 0] [2 0]
one new shuffled column will make the matrix
[2 0 0] [3 0 1] [6 0 0] [2 0 0]
but NOT
[2 0 0] [3 0 0] [6 0 1] [2 0 0]
because i don't wont to shuffle the rows that have 6 with the rows that have 2-5. I want with this process to create 100 new columns and to do this 2008 times with different matrixes of the same size. All this shuffling has to be in a random way except for the condition of 2-5 and 6 that I mentioned.

采纳的回答

the cyclist
the cyclist 2018-6-1
编辑:the cyclist 2018-6-1
I think this does what you want. I wrote it from more of a didactic than efficiency approach. I imagine there are some efficiencies here, but one should generally get a working solution first, then consider optimization.
NCOL = 100;
M = [2 1;
3 0;
2 0;
4 0;
6 1;
2 1;
6 0];
M_new = [M, zeros(size(M,1),NCOL)];
isRowSix = M(:,1)==6;
isRowNot = M(:,1)~=6;
M2Six = M(isRowSix,2);
M2Not = M(isRowNot,2);
numberRowsSix = sum(isRowSix);
numberRowsNot = sum(isRowNot);
for nc = 1:NCOL
newOrderSix = randperm(numberRowsSix);
newOrderNot = randperm(numberRowsNot);
newColSix = M2Six(newOrderSix);
newColNot = M2Not(newOrderNot);
M_new(isRowSix,nc+2) = newColSix;
M_new(isRowNot,nc+2) = newColNot;
end
  3 个评论
the cyclist
the cyclist 2018-6-4
% The number of additional columns
NCOL = 100;
% The original data
M = [2 1;
3 0;
2 0;
4 0;
6 1;
2 1;
6 0];
% Preallocate the new array
M_new = [M, zeros(size(M,1),NCOL)];
% Identify the rows that have a 6 in the first column (and those that do not)
isRowSix = M(:,1)==6;
isRowNot = M(:,1)~=6;
% Get the 2nd-column values for the 6 rows (and the not-6 rows)
% These values will get separately shuffled
M2Six = M(isRowSix,2);
M2Not = M(isRowNot,2);
% The count of rows with 6's (and not)
numberRowsSix = sum(isRowSix);
numberRowsNot = sum(isRowNot);
% For each additional column ...
for nc = 1:NCOL
% Create a random permutation of the values from the rows with 6's (and those not)
newOrderSix = randperm(numberRowsSix);
newOrderNot = randperm(numberRowsNot);
newColSix = M2Six(newOrderSix);
newColNot = M2Not(newOrderNot);
% Insert those pemutations into the new array
M_new(isRowSix,nc+2) = newColSix;
M_new(isRowNot,nc+2) = newColNot;
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by