Selection with no direct repeatition

2 次查看(过去 30 天)
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