Selection with no direct repeatition

조회 수: 2 (최근 30일)
Hamzah Faraj
Hamzah Faraj 2020년 4월 22일
답변: Hamzah Faraj 2020년 4월 22일
Hello everyone,
I want to create 10 vectors with the following conditions:
Element number (i) is not equal to element number (i+1) and they have to be selected from set "a".
Length of each vector is 10 elements.
I am new to programming and I'd appreciate it if you can help me.
Here is me attempt:
%------------------------------------------------------------------------%
clear variables;
close all;
clc;
%------------------------------------------------------------------------%
%% variables definition
n=10;
a=[0 4/3 2];
n1=nan;
%------------------------------------------------------------------------%
%% memory allocation
%------------------------------------------------------------------------%
i1=zeros(1,n);
i2=zeros(1,n);
n1=zeros(1,n);
n2=zeros(1,n);
%------------------------------------------------------------------------%
%% selection process
for i=1:n
i1(i) = randi(length(a));
n1(i) = a(i1(i));
i2(i) = randi((length(a)-1)); % to provide better selection ( picking from 2 element instead of 3)
i2(i) = i2(i) + (i2(i) >= i1(i));
n2(i) = a(i2(i));
while (n1==n2)
n2(i) = a(i2(i));
end
n1=n2;
end
n2

채택된 답변

Hamzah Faraj
Hamzah Faraj 2020년 4월 22일
idxr = randi(length(a),1,10); %// create the first batch of numbers
idx = diff(idxr)==0; %// logical array, where 1s denote repetitions for first batch
while nnz(idx)~=0
idx = diff(idxr)==0; %// logical array, where 1s denote repetitions for
%// subsequent batches
rN = randi(length(a),1,nnz(idx)); %// new set of random integers to be placed
%// at the positions where repetitions have occured
idxr(find(idx)+1) = rN; %// place ramdom integers at their respective positions
end
r=a(idxr);
end

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 4월 22일
  댓글 수: 1
Hamzah Faraj
Hamzah Faraj 2020년 4월 22일
hello Amer,
Thank you for your attempt to answer the question. However, this is not the right answer as this generates random numbers, but not from set a in the question.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by