Simulation stopped because of a runtime error

6 views (last 30 days)
Maryam Nezami
Maryam Nezami on 31 May 2019
Answered: Rajanya on 16 Apr 2025
Hello everyone,
I have written a function in matlab. Now I want to use it in Simulink.
In my matlab code, I have a for loop. In each step different matricies are produced based of the step which the for loop is being run.
Now how should I change my function to be usable in simulink? I want the simulink to calculate and use different matrices in each simulation step.
Right now, I have used a digital clock. But, the for loop has an error. I need to determine matricies dimension based on the step which the system is working. I am getting negative values so I cannot make my matricies.
Can anyone please take a look at the simulink and help me with it?
P.S. I have simplified the simulink.

Answers (1)

Rajanya
Rajanya on 16 Apr 2025
The error is because the following expression '100-max(size(k))-100' evaluates to a negative integer within 'zeros' -
zeros(100-max(size(k))-100,1) ---> zeros(100-(100)-100,1) ---> zeros(-100,1)
As per documentation, negative input arguments within 'zeros' function are treated to be 0 and 'zeros(-100,1)' gives an empty double column vector when run in MATLAB.
But in Simulink, MATLAB Function blocks are stricter (for reasons of code generation) and whenever a negative argument, which is dependent on the input to the Function block, is used in the 'zeros' function in the MATLAB Function block, it errors out.
The following simple model demonstrates the behaviour -
Here, an input argument to the 'zeros' function is dependent on the input variable 't' and evaluates to -1. Hence we get the error:
However, the error does not come up when the negative input arguments to the 'zeros' function, if used, do not depend on any input data. For example, if 'val', in the above code, is changed to the following, the model runs just fine -
val = zeros(-1,1); %no error here
The same issue is coming up in your model, since the 'zeros' in the MATLAB Function Block is accessing a negative input argument, which is dependent on the input to the function, causing the error.
To prevent such errors, you can wrap the expression used in 'zeros' in a way such that if the expression ever evaluates to < 0, it gets treated as zero. For example, changing the original expression to the following, avoids all such errors.
zeros(max(100-max(size(k))-100,0),1)
% Wrapping the suspected expression with a max()such that when the expression
% evaluates to negative values, it is replaced with 0.
Hope this helps!

Categories

Find more on Simulink in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!