Rearrange an array based on a matrix

조회 수: 1 (최근 30일)
luca
luca 2019년 10월 3일
댓글: luca 2019년 10월 3일
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일
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
meghannmarie
meghannmarie 2019년 10월 3일
It looks like its working to me.
luca
luca 2019년 10월 3일
My mistake! Sorry and thanks. Again

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

추가 답변 (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