Rearrange an array based on a matrix
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponse acceptée
meghannmarie
le 3 Oct 2019
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!