Populate a vector to a specified threshold limit

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

采纳的回答

Fangjun Jiang
Fangjun Jiang 2011-11-9
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 个评论
Matt
Matt 2011-11-9
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by