Given the following arrays
V= [4,2,4,2,1,1,4,2,1,2,6,2,2,4,6,1,2,6,2,2,2,6,8,8,7,7,8,7,7,7,7,8,7,7,6,6,9,9,9,8,8,8,9,8,9,8,9,8,9]
I want to randomly mix the vector but following a rule
In fact, given a matrix
M = [1 6 7 9;
2 0 8 0;
4 0 0 0]
I want to randomly mix the values in V that are in the same column of M mainting the same position in V. It means that a place take by 1 can be randomly substituted by a 2 or a 4. It's important that the position inside the array V doesn't change, what has to change is just the value. For what concerne 6, in this case we have only 6, so it will be the same. For what concerne 7 and 8, they will randomly mix inside the array V exchange their value but mantain the same position (same column index).
making an example with a shorter vector
V = [6 7 6 1 2 4 9 9 9 6 7 4 7 1]
I would like to obtain a random array like
V = [6 8 6 4 1 4 9 9 9 6 7 4 8 2]
for example in the fourth column we had a 1, with the random permutation I want to randomly subsituted 1 with 1,2 or 4 (based on M column).
I hope the request is clear.
May someone help me with this task?

 채택된 답변

meghannmarie
meghannmarie 2019년 10월 3일

0 개 추천

Would something like this work:
for i = 1:numel(V)
[~,k] = find(M == V(i));
col_v = M(:,k);
col_v = col_v(col_v ~= 0);
ridx = randi(numel(col));
V(i) = col(ridx);
end

댓글 수: 3

V= [11,3,11,3,3,11,3,11,11,3,11,11,11,11,2,2,2,11,2,2,11,2,2,2,2,11,2,11,11,11,11,11,1,11,1,1,1,11,1,11,1,8,8,1,8,8,1,8,1,1,1,9,9,9,9,12,1,9,9,9,9,1,12,9,12,12,12,9,9,9,12,9,9,12,12,1,12,1,9,12,13,7,7,7,7,7,13,9,9,13,13,7,13,13,13,13,7,13,13,7,13,7,13,9,9,9,7,13,13,13,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,4,5,10,5,10,5,10,5,10,5,10,5,10,6,10,6,10,6,10,6,10,6];
M= [1 3 2 4 5 8 9 11;
0 0 0 7 6 12 0 0;
0 0 0 0 10 13 0 0];
for i = 1:numel(V)
[~,k] = find(M == V(i));
col_v = M(:,k);
col_v = col_v(col_v ~= 0);
ridx = randi(numel(col_v));
V(i) = col_v(ridx);
end
Hi, could you tell me why in this case it doesn't work?
meghannmarie
meghannmarie 2019년 10월 3일
It looks like its working to me.
luca
luca 2019년 10월 3일
My mistake! Sorry and thanks. Again

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2019년 10월 3일

댓글:

2019년 10월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by