필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Hang Vu
Hang Vu 2019년 4월 29일
편집: Jan 2019년 4월 30일
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
between same bumber can be no number
for example : C=[1 8 6 1 2 5 3 2 7 11 7 9 10 9]
or C=[1 1 2 5 3 8 2 7 11 6 7 9 10 9]
or C=[1 1 2 5 8 3 2 7 11 6 10 7 9 9]
I asked from another question for help and recieved the below code. But it is not flexible for position of non-number
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.
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,Na/2-1)
Xa = diff([0,sort(Xa),Nb]) % the number of elements of B to pick.
end
T = [num2cell(A(1:2:Na));mat2cell(B(Xb),1,Xa);num2cell(A(2:2:Na))];
C = [T{:}]

채택된 답변

Jan
Jan 2019년 4월 29일
편집: Jan 2019년 4월 30일
A = [1 1 2 2 7 7 9 9];
B = [3 5 6 8 10 11];
nA = numel(A);
nB = numel(B);
rB = B(randperm(nB, nB)).';
iA = randi([1, nA/2], nB, 1); % Each value of B gets a bin in A
C = accumarray(iA, rB, [nA/2, 1], @(x) {x});
AC = num2cell(A(1:2:nA).'); % same as for A(2:2:nA)
T = [AC, C, AC].';
Result = vertcat(T{:}).'
  댓글 수: 1
Hang Vu
Hang Vu 2019년 4월 30일
It is exactly what I want, Thank you so much for the help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by