MATLAB Answers

luca
0

Rearrange an array based on a matrix

Asked by luca
on 3 Oct 2019
Latest activity Commented on by luca
on 3 Oct 2019
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 Comments

Sign in to comment.

Products


Release

R2019b

1 Answer

Answer by meghannmarie on 3 Oct 2019
 Accepted Answer

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 Comments

luca
on 3 Oct 2019
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?
It looks like its working to me.
luca
on 3 Oct 2019
My mistake! Sorry and thanks. Again

Sign in to comment.