Effacer les filtres
Effacer les filtres

How can I create a random array like the example C?

1 vue (au cours des 30 derniers jours)
Hang Vu
Hang Vu le 25 Avr 2019
Commenté : Hang Vu le 29 Avr 2019
A=[1 1 2 2 7 7 9 9]
B=[3 5 6 8 10 11] : randomly choose all items from B and input between 2 same number of A
for example : C=[1 8 6 1 2 5 3 2 7 11 7 9 10 9]
  4 commentaires
Jan
Jan le 25 Avr 2019
Please mention the details: Does the result need to have at least one value of B between the equal elements of A? Does the order of elements of B matter? Does A have an even number of elements in every case so the new elements can be inserted at the indices 2, 4, 6, ...? Providing 1 example does not define the problem completely.
Hang Vu
Hang Vu le 26 Avr 2019
Thank you Jan! yes at least one value of B between 2 same number of A, and the B'order is no matter. And A is has 2 same number for each elements so it's even number of elements.

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 26 Avr 2019
Modifié(e) : Stephen23 le 26 Avr 2019
A = [1,1,2,2,7,7,9,9];
B = [3,5,6,8,10,11];
Na = numel(A);
Nb = numel(B);
Xb = randperm(Nb) % to shuffle the order of B.
Xa = randperm(Nb-1,Na/2-1);
Xa = diff([0,sort(Xa),Nb]) % the number of elements of B to pick.
T = [num2cell(A(1:2:Na));mat2cell(B(Xb),1,Xa);num2cell(A(2:2:Na))];
C = [T{:}]
Giving (for example):
Xb =
4 6 3 2 1 5
Xa =
1 2 2 1
C =
1 8 1 2 11 6 2 7 5 3 7 9 10 9
  6 commentaires
Hang Vu
Hang Vu le 26 Avr 2019
Modifié(e) : Hang Vu le 29 Avr 2019
I just realized I didn't change B to Iminus. Now it works well. Thank you so much!^^
Hang Vu
Hang Vu le 29 Avr 2019
Could you please help me more on this! for all cases, can be either pick 1 1 or 2 numbers!
Xb =
1 2
Xa =
0 1 1 0 => 0 0 2 0
C =
1 1 2 3 2 7 5 7 9 9 => 1 1 2 2 7 3 5 7 9 9
if Nb<=Na/2 % "if don't have enough B to fill in"
Xa = zeros(1,Na/2);
Xa(randperm(Na/2,Nb)) = 1; % the number of elements of B to pick.
else
Xa = randperm(Nb-1,Na/2-1);
Xa = diff([0,sort(Xa),Nb]) % the number of elements of B to pick.
end
and it's possible to have 0 for all cases, not only Nb<=Na

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices 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!

Translated by