Populate a vector to a specified threshold limit

1 visualización (últimos 30 días)
Matt
Matt el 9 de Nov. de 2011
Hi; I'm trying to generate an array by calculating 'y from a large list of random numbers 'x', but I want the vector to stop populating once it reaches 5000 entries.
Here's the code to generate the vector (and reject all values less than -5 and greater than 25)
a=10; T=3;
x = rand(10000,1);
y=a+((T/2).*(tan(pi.*(x-(0.5)))));
y(y<-5)=[];
y(y>25)=[];
So this generates entries in the vector 'y', but I want the vector to stop populating after it reaches 5000 entries. I've tried using a while loop and playing around with counting the entries in the array then trying to break out of the loop, but I can't seem to get it to work. Any help is appreciated! Thanks!

Respuesta aceptada

Fangjun Jiang
Fangjun Jiang el 9 de Nov. de 2011
Can you generate a reasonably large random number, e.g. x=rand(50000,1), then after y(y<-5)=[] and y(y>25)=[] operation, it is almost certain that y is more than 5000 in length? Then you can do y(5001:end)=[].
It is certainly possible to do it using a while-loop, but probably won't be fast.
a=10; T=3;
y=zeros(5000,1);
k=1;
while k<=5000
x= rand;
temp=a+((T/2).*(tan(pi.*(x-(0.5)))));
if -5<=temp && temp<=25
y(k)=temp;
k=k+1;
end
end
  1 comentario
Matt
Matt el 9 de Nov. de 2011
Hah, you know the expression 'can't see the forest for the trees'....
Funny that I didn't think of just deleting the leftovers at the end of a large vector. That works perfectly and yes if you use enough values, you keep the random nature of the problem.
Thanks!
PS: you're right about the speed of the while-loop taking a very long time

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Numeric Types 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