在Matlab中用作索引的随机数 [英] Random number to be used as index in matlab
问题描述
我无法获取矢量packet_send的整数索引.(基本上,我正在生成1到100之间的随机索引).当我看到用作索引的长度"类为double时,这意味着rand函数返回double值,因此我厌倦了通过将其类型转换为int16将其转换为整数.但是我仍然没有得到想要的长度,因此我可以将其用作向量的索引.
Well I am unable to get the integer index for the vector packet_send. ( Basically I am generating a random index between 1 to 100). When I saw the class of "lengths" which I am using as index it is double, that means rand function returns double value, so I tired converting it to integer by typecasting it to int16. But still I am not getting the desired lengths, so that I can use it as index for the vector.
for time_slot = 1:1:number_of_slots
p = randint(1)*prob;
lengths =int16( round(rand(1) * max_length)); % lengths value between 1 to 100.. as per the range decided
if (p == prob)
packet_send(lengths) = packet_send(lengths) + 1;
total_number_of_packets = total_number_of_packets + 1 ;
end
end
推荐答案
You can use randi
to create random integers. For your code example, this could read:
lengths = randi(max_length, 1);
您还可以在循环开始之前绘制所有随机索引:
You could also draw all the random indices before the loop starts with:
allLengths = randi(max_length, number_of_slots);
〜编辑〜
如果 randi
在您的Matlab版本中不可用,则可以使用:
~edit~
If randi
is not available in your version of matlab, you can use:
lengths = floor(rand(1)*max_length)+1;
这篇关于在Matlab中用作索引的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!