Calls to coder.extrinsic in inner-level of Matlab/Simulink

19 views (last 30 days)
Hi. I need to generate random numbers in normal distribution in Simulink. I use this code in one of my functions:
coder.extrinsic('random');
x=random('rand',0,1);
but I'm getting this error:
Calls to coder.extrinsic may only appear at the top-level.
Is there anyone to help me?

Accepted Answer

Walter Roberson
Walter Roberson on 27 Jul 2015
Is the coder.extrinsic() call within a loop or control structure? If so then move it to be outside those (but still in the function.)
  7 Comments
Mike Hosea
Mike Hosea on 7 Aug 2015
The term "extrinsic" means you're going outside of the normal system to get the job done. Here, you're contracting out evaluation to MATLAB like some kind of server, and MATLAB communicates to its clients using a data type called an "mxArray". It has data inside it, but that data can be anything. The mxArray itself tells what's inside of it, which would be fine if the MATLAB Function Block could wait until you actually call the function to decide what to do. It can't, however. It must figure out what will be inside of the array before the simulation even starts. The way you tell the block that is by pre-defining the variable you will use to hold the output of the extrinsic function call.
Since this extrinsic function call will return a scalar double value, in this case you would use
rho = 1
noise = 0;
noise = normrnd(0,rho);
temp = noise + 1;
But why do you need to use an extrinsic call for a random normal? Just use the RANDN function like so:
noise = mu + sd*randn;
Or if you upgrade to R2013b, you can call NORMRND or RANDOM without making it extrinsic.
Marie Behzadi
Marie Behzadi on 8 Aug 2015
Thanks. It worked. I will try to upgrade to R2013b. but the first solution you described just worked fine. Thank you all :)

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 7 Aug 2015
There's a block to do this. Perhaps you can pass the signal from this block into your function as an input?
  1 Comment
Marie Behzadi
Marie Behzadi on 8 Aug 2015
I tried this method. but I need to change the variance each time step. When I use this block and I read the variance from workspace, It only uses the first value. It also doesn't have an input port.

Sign in to comment.

Categories

Find more on Simulink Functions in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!