Selection with no direct repeatition

1 回表示 (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by