Borrar filtros
Borrar filtros

Selection with no direct repeatition

1 visualización (últimos 30 días)
Hamzah Faraj
Hamzah Faraj el 22 de Abr. de 2020
Respondida: Hamzah Faraj el 22 de Abr. de 2020
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

Respuesta aceptada

Hamzah Faraj
Hamzah Faraj el 22 de Abr. de 2020
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

Más respuestas (1)

Ameer Hamza
Ameer Hamza el 22 de Abr. de 2020
  1 comentario
Hamzah Faraj
Hamzah Faraj el 22 de Abr. de 2020
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by