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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by