Using a MATLAB function-block in Simulink to generate random numbers

13 views (last 30 days)
Hello!
I've tried to both google this question and search among the questions and answers here, but I've found no definitve answer to my question so I'm making a new one. Hopefully it won't be too much trouble!
I'm creating a simulation in Simulink where I have a "MATLAB function"-block that is supposed to take input from another source (we can consider this source a "Constant"-block) and then apply a random number that is generated from the MATLAB function-block on the input.
My problem is that I get the exact same randomized numbers every single time I run the Simulink simulation. And I was wondering if someone could help me solve my problem?
Here is the code (not all of it, but all of it that matters):
% 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
I've read about this solution, but it doesn't work for me
coder.extrinsic('rng');
rng('shuffle');
In different ways but with no success. Some help would be greatly appriciated! Oh, and btw, I'm using MATLAB R2012a.
Thanks in advance, Niklas

Answers (1)

A Jenkins
A Jenkins on 25 Jun 2014
Add also:
coder.extrinsic('rand')
to the beginning of your code.
  2 Comments
Niklas
Niklas on 25 Jun 2014
After adding that MATLAB tells me that the line:
rand_numbers = Stat_input*minrand + rand(1).*(maxrand-minrand);
Gets the following error:
Expected either a logical, char, int, fi, single, or double. Found an mxArray. MxArrays are returned from calls to the MATLAB interpreter and are not supported inside expressions. They may only be used on the right-hand side of assignments and as arguments to extrinsic functions.
Any idea why?
A Jenkins
A Jenkins on 25 Jun 2014
function MC_output = fcn(Stat_input)
coder.extrinsic('rng');
coder.extrinsic('rand')
rng('shuffle');
minrand = 0.1;
maxrand = 1.9;
points = 10;
z=zeros(1, points);
z=rand(1, points);
rand_numbers = Stat_input*minrand + z.*(maxrand-minrand);
MC_output = mean(rand_numbers);
end

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!