MATLAB Answers

How to create array in Simulink with MATLAB function?

224 views (last 30 days)
mettala
mettala on 22 Feb 2016
Commented: mettala on 26 Feb 2016
I have a Simulink model where I need to create an array based on two integers, say n and m. n and m are results from previous Simulink calculations and they change at each time step. If I would do this in MATLAB alone, I would do it in this way:
A = n:1:m
I tried to create a MATLAB function block with following code (which doesn't obviously work):
function A = fcn(n,m)
%#codegen
assert (n < 100);
assert (m < 100);
A = (n:1:m);
Both n and m are below 100. Someone had similar problem 5 years ago, but didn't receive an answer.
I get an following error message:
Computed maximum size of the output of function 'colon' is not bounded.
Static memory allocation requires all sizes to be bounded.
The computed size is [1 x :?].
I'm relatively new with MATLAB and Simulink and I just can't find a solution to my problem. Is there a suitable pre-made block for me or is there something I can do to improve my MATLAB function?
Once created, the array will be spit into While Iterator Subsystem, where each value will be individually modified based on few if-operators.

  0 Comments

Sign in to comment.

Accepted Answer

Anish Mitra
Anish Mitra on 25 Feb 2016
Simulink does not allow dynamically changing the size (dimensions) of any signal while the simulation is running. This is because the size needs to consistent as states are propagated from one time step to the next.
In this situation, I would recommend creating an array of fixed length depending on the lower bounds of n and m, and then assigning the values based on n and m. You will also need to specify in the Model Explorer that the signal is variable sized, but with an upper bound. This would mean having specific numbers in the "Size" field, but check the box "Variable size".
Another issue to keep in mind is to have specific sample times for the inputs to the MATLAB Function block. The code and screenshots below demonstrate an example.
function y = fcn(n,m)
%#codegen
assert (n < 5);
assert (m < 5);
assert(n >= -5);
assert(m >= -5);
y = n:m;
%

  1 Comment

mettala
mettala on 26 Feb 2016
Thank you for your answer! This solved my problem.

Sign in to comment.

More Answers (0)