【问题标题】:Generating random numbers in Simulink with MATLAB function-block使用 MATLAB 功能块在 Simulink 中生成随机数
【发布时间】:2014-06-25 13:47:56
【问题描述】:

我尝试在谷歌上搜索这个问题并在此处的问题和答案中进行搜索,但我没有找到我的问题的明确答案,所以我正在制作一个新问题。希望不会太麻烦!

我正在 Simulink 中创建一个模拟,其中我有一个“MATLAB 函数”块,它应该从另一个源获取输入(我们可以将此源视为“常量”块),然后应用一个随机数从输入上的 MATLAB 功能块生成。

我的问题是每次运行 Simulink 仿真时都会得到完全相同的随机数。我想知道是否有人可以帮助我解决我的问题?

这里是代码(不是全部,而是所有重要的):

% function MC_output = randomizer(Stat_input)
%#codegen    minrand = 0.1;
    maxrand = 1.9;
    points = 10;    
    rand_numbers = Stat_input*minrand + rand(1, points).*(maxrand-minrand);
    MC_output = mean(rand_numbers);
end

我已阅读有关此解决方案的信息:

coder.extrinsic('rng');
rng('shuffle');

我以不同的方式使用它,但没有成功。一些帮助将不胜感激!哦,顺便说一句,我使用的是 MATLAB R2012a。

提前致谢,尼克拉斯

【问题讨论】:

    标签: matlab random simulink matlab-coder


    【解决方案1】:

    从您的 MATLAB Fcn 模块调用的 rand 与从 MATLAB 调用的 rand 不同,因此 rng('shuffle'); 对 Simulink 的随机数生成没有影响。

    您可以强制 MATLAB Fcn 块使用 MATLAB 的 rand 函数,方法是:

    function y = fcn
    %#codegen
    coder.extrinsic('rand','rng');
    y = 0;
    
    persistent atTime0
    if isempty(atTime0)
        rng('shuffle');
        atTime0 = false;
    end
    
    y = rand;
    

    或者您可以使用旧式方法重置随机数的种子

    function y = fcn(seed)
    %#codegen
    
    persistent atTime0
    if isempty(atTime0)
        rand('seed',seed);
        atTime0 = false;
    end
    
    y = rand;
    

    但更简单的方法是将随机数/向量作为 Uniform Random Number Generator 块生成的输入提供,并随机设置其 seed 参数(使用 MATLAB 的 rand 函数)。

    【讨论】:

    • 非常感谢!这正是我一直在寻找的,而且效果很好! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    相关资源
    最近更新 更多