matlab for loop hang

时间:2013-01-20 01:27:13

标签: matlab for-loop logic

我正在为for循环做模拟和代码

例如

IntervalInterArrivalTime = [2 3 4 5] //user input 
CDF = [250 500 750 1000] // this is the probability but multiply 1000 to alculate the range
randInterArrival = [991 351 754 823] // this is pc random generated number so each time wwill be different 

lengthCDF = length(CDF); // length of the CDF which in this case is =4
period = 0;

我想要的for循环是程序将使用CDF和IntervalArrivalTime检查randInterArrival的范围。例如:

如果randInterArrival> 0和< = CDF(1),则句点为IntervalInterArrivalTime(1)

否则如果randInterArrival> CDF(1)和< = CDF(2),那么期间将是IntervalInterArrival(2)

否则如果randInterArrival> CDF(2)和< = CDF(3),那么句号将是IntervalInterArrival(3)

否则如果randInterArrival> CDF(3)和< = CDF(4),那么句号将是IntervalInterArrival(4)

for i=1:lengthCDF
if randInterArrival(i)>0 && randInterArrival(i)< CDF(i)
 period=IntervalInterArrivalTime(i)
else if randInterArrival(i)> CDF(i) % how to continued to write the statement out so that i can loop through all the items in the CDF and check which IntervalInterArrival() it is

% i stop here and dunno how to continued to loop through the CDF and check
end
end
希望你们都能提供帮助。提前谢谢

2 个答案:

答案 0 :(得分:4)

可以以你提议的方式做到这一点,分别检查每个条件。但是,当您增加要检查的元素/条件的数量时,这会变得令人讨厌。更好的方法是利用find函数和重新思考您尝试做的事情的逻辑:

目标是什么?目标是确定大于CDF的最小randInterArrival(i)值的索引。这样做如下:

index = find(CDF > randInterArrival(i), 1, 'first');

瞧!不需要if个陈述。使用此索引获取句点:

period = IntervalInterArrivalTime(index);

答案 1 :(得分:0)

您需要end您的陈述:

for i=1:lengthCDF
if randInterArrival(i)>0 && randInterArrival(i)< CDF(i)
 period=IntervalInterArrivalTime(i)
else if randInterArrival(i)> CDF(i) && ?? // i hang here .. 
end
end