Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

how do i create a loop that generates random numbers in between .5 and five seconds(.5+4.5*rand), that accumulates up to 60 seconds then resets back to zero seconds for 120 times

Asked by George on 30 Nov 2012

I have been trying to do this for two days and have a cluster f of variables which in the end doesn't work. I also need a separate variable to count up all the time passed??

this is what i have it just keeps going up and doesn't reset at 60 seconds

clc 
clear
n=7200;
rlight=35;
glight=60-rlight;
x=zeros(n,1);
greencars= zeros(n,1);
inqueue=zeros(n,1);
for i=1:n;
    while x<=floor(7140)
    x=(.5+4.5*rand)+x;
    if x<glight
        greencars(i,1)=greencars(i,1)+1;
    elseif x>=glight & x<=60
        inqueue(i,1)=inqueue(i,1)+1;
    end 
    end
end
gcars=sum(greencars)
inqueue=sum(inqueue)
wait=inqueue;
line=wait-1;
sec_cross=3.2+line*1.4
go=glight-sec_cross
max(x)

9 Comments

Walter Roberson on 30 Nov 2012

The random numbers do not cycle from 0:60. The random numbers are 0.5 to 5.

I suggest you use mod()

There is no need to treat the first cycle differently: just initialize the queue to be empty.

Muruganandham Subramanian on 30 Nov 2012

I suggest you to use linspace()

Walter Roberson on 30 Nov 2012

I don't think linspace() will have much use in this question.

George

Products

No products are associated with this question.

1 Answer

Answer by Jan Simon on 30 Nov 2012

Perhaps this helps:

T      = 0.5 + rand(1,1e6) * 4.0;         % Times
accumT = cumsum(t);                       % Accumulated times
phaseT = rem(accumT, 60);                 % Green phases
phases = find([true, diff(phaseT <= 0));  % Indices of green phases

The duration of the red phase does not matter, as far as I can see. It can be added at the phases to the timings without touching the rest of the calculations.

0 Comments

Jan Simon

Contact us