Exchange position of elements in an array

2 ビュー (過去 30 日間)
luca
luca 2019 年 10 月 7 日
回答済み: David Hill 2019 年 10 月 7 日
Hi given two arrays
SP = [1 2 3 4 8 11 13 14 15 16 18 19 20];
Y= [24 18 18 18 18 18 18 18 18 18 18 18 18];
I create an array
S= [19 1 4 14 20 11 20 13 18 11 8 16 14 13 3 13 8 1 15 13 16 14 1 11 3 4 20 19 8 20 14 18 3 11 13 13 11 20 11 20 16 2 20 15 1 11 4 13 18 20 3 15 11 8 16 8 14 14 1 8 14 8 1 16 3 20 8 18 16 4 15 2 8 2 3 16 14 3 15 2 1 18 13 4 18 4 20 18 14 4 2 2 2 4 8 11 20 13 3 11 16 19 2 18 3 11 19 1 13 3 19 11 15 3 14 19 16 2 8 13 3 11 20 19 18 18 19 15 14 16 8 1 3 18 18 4 14 15 15 18 1 3 4 1 15 2 11 1 16 15 8 13 16 16 1 19 16 13 19 8 19 11 20 1 15 2 13 14 20 1 2 8 14 4 15 15 4 1 1 3 18 1 4 4 1 8 11 2 1 18 14 18 13 8 14 19 3 18 11 4 11 20 16 1 15 15 19 2 19 3 2 20 13 19 4 13 15 4 16 1 8 19 1 3 19 16 2 4 14 2 14 1 16 19 15 20 2 20 13 18];
Where 1 is repeated 24 times, 2 is repeated 18 times, 3 is repeated 18 times and so on. So the array SP tells us the diversity of elements and Y how many times they are repeated in S.
Now what I want to do is to exchange randomly the position of the elements inside S.
In particular I want to follow two rules:
1) Just some elements can exchange with eachother. In particular considering the matrix BB
BB= [1 2 3 4 0 11 14 15;
0 0 0 8 13 16 0 0;
0 0 0 0 0 18 0 0;
0 0 0 0 0 19 0 0;
0 0 0 0 0 20 0 0];
We can exchange each other just the element on the same column. It means that a 11 can just exchange with 16,18,19,20. While 4 can just exchange with 8. Obviously if there is just one number on the columns it will remain in its position.
2) I want that the elements exchange their position randomly with the one on the same columns of BB. But I don't want to substitute a value with another random value on the same colums! This means that at the end, the number of repetitons indicated in Y will be respected in the new array
May someone can help me with this code?

採用された回答

David Hill
David Hill 2019 年 10 月 7 日
for i=1:size(BB,2)
x=S(ismember(S,BB(:,i)));
S(ismember(S,BB(:,i)))=x(randperm(length(x)));
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by