필터 지우기
필터 지우기

Try to mix as much as possible elements inside an array

조회 수: 1 (최근 30일)
luca
luca 2019년 9월 17일
편집: Adam Danz 2019년 9월 23일
Given a vector
V = [1 1 1 1 1 1 1 4 4 4 4 4 1 1 1 1 1 4 4 4 4 4 4 5 5 5 5 5 5 8 8 8 8 8 8 5 5 5 5 5 5 5 5 6 6 6 6 6 6 8 8 8 8 5 5 5 5 6 6 7 7 7 7 7 9 9 9 9 9 7 7 7]
I would like to destroy the consecutivity of the same number and mix the elements. In particular I want to mix 1 just with 4, 5 just with 6-8 and 7 just with 9.
obtaining for example:
S = [1 1 4 1 4 1 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 4 5 5 8 5 8 5 8 5 8 5 8 6 5 5 6 5 5 5 8 5 6 8 6 5 6 5 8 6 5 8 5 6 5 5 8 6 7 9 7 7 7 9 7 9 7 9 7 9 7]
It's not important the way I mix but it's important the consecutivity: first 1-4 then 5-8-6 and finally 7-9
May someone help me to find a way to obtain S?
  댓글 수: 3
Aquatris
Aquatris 2019년 9월 17일
편집: Adam Danz 2019년 9월 23일
Check the function randperm(). Then you can create an index vector and shuffle the elements to obtain what you want.
luca
luca 2019년 9월 18일
편집: luca 2019년 9월 18일
I've changed the structure in order to avoid this problem, but I'm still interested in knowing if there is a solution for that
Thanks

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

채택된 답변

Adam Danz
Adam Danz 2019년 9월 18일
The 'exchangeOpts' is a list of exchange options such that any value in V that matches a value in exchangeOpts{n} can be replaced with a random value from exchangeOpts{n}.
V = [1 1 1 1 1 1 1 4 4 4 4 4 1 1 1 1 1 4 4 4 4 4 4 5 5 5 5 5 5 8 8 8 8 8 8 5 5 5 5 5 5 5 5 6 6 6 6 6 6 8 8 8 8 5 5 5 5 6 6 7 7 7 7 7 9 9 9 9 9 7 7 7];
exchangeOpts = {[1,4],[5,6],[7,9]}; %identify exchange groups (in cell array to allow for mixed vector sizes)
% loop through each exchange option
S = V;
for i = 1:numel(exchangeOpts)
idx = ismember(V,exchangeOpts{i}); %identifies which elements will be randomized
S(idx) = exchangeOpts{i}(randi(numel(exchangeOpts{i}),1,sum(idx)));
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating 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