How to generate a random distribution.
古いコメントを表示
Hi I'm doing a simple project for a course I'm in and I've been having trouble with some of the scripts my prof gives us. I think its because they're written for an older version of Matlab. I'm using matlab 2014a.
I think this code is supposed to generate a random distribution for x, but when I run it x ends up getting a stuck value, I know that's not supposed to happen. Can some one help?
function x=creature_state()
x=floor(2.1*rand)+1;
return
4 件のコメント
David Young
2014 年 7 月 11 日
I'm not sure what you mean by a stuck value. The function returns the value 1, 2 or 3, with 3 being relatively rare. You expect there to be occasional long runs of 1s or 2s (and less often 3s). That's what I observe from it. I'm using 2013b but I'd be surprised if something as fundamental as rand is broken in 2014a.
dpb
2014 年 7 月 11 日
Indeed...a representative sample from looks like--
>> histc(floor(2.1*rand(1000,1))+1,[1:3])
ans =
471
490
39
>> ans/sum(ans)
ans =
0.4710
0.4900
0.0390
>>
Dalas
2014 年 7 月 12 日
David Young
2014 年 7 月 12 日
Sounds like the problem is with the code that calls creature_state, not with creature_state itself. I think you need to show the relevant part of the calling code. (Best to edit the question to include it.)
回答 (1 件)
Image Analyst
2014 年 7 月 11 日
0 投票
Did you know that floor rounds down to the nearest integer? If you want unique values, get rid of the floor. It has nothing to do with the version of MATLAB either of you are using.
3 件のコメント
Dalas
2014 年 7 月 12 日
Image Analyst
2014 年 7 月 12 日
You can use randi(3, 1) to get a random number between 1 and 3. It's an integer though actually of class "double" rather than int32. It would be preferable than using that code you have.
Image Analyst
2014 年 7 月 12 日
Regarding your comment above. It does not get stuck. Look at my test3.m where I call you function:
function test3
clc; % Clear command window.
x=creature_state()
x=creature_state()
x=creature_state()
x=creature_state()
x=creature_state()
x=creature_state()
function x=creature_state()
x=floor(2.1*rand)+1;
return
Now, look at the command window:
x =
1
x =
2
x =
3
x =
3
x =
1
x =
3
Do you see that x is always the same value every time? I don't.
カテゴリ
ヘルプ センター および File Exchange で Univariate Discrete Distributions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!