Clear Filters
Clear Filters

Populate a vector to a specified threshold limit

3 views (last 30 days)
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!

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 9 Nov 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 Comment
Matt
Matt on 9 Nov 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

Sign in to comment.

More Answers (0)

Categories

Find more on Data Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!