Error: new fields cannot be added when structure has been read or used only in Simulink using Matlab Function

Hi everyone,
I have a question why the code
e=7
b(e);
function a = b(t)
cest.d=t;
cest.e=cest.d;
a=cest.e;
end
works fine in Matlab, but not in Simulink. In Simulink I create a Constant Block with the value 7, in addition I create a Matlab Function Block in which I insert this code
Simulink Modell
function a = b(t)
cest.d=t;
cest.e=cest.d;
a=cest.e;
end
and pass the obtained value to the Matlab workspace.
In theory, this should also work in Simulink. But I always get the error message This structure does not have a field 'e'; new fields cannot be added when structure has been read or used.
Function 'MATLAB Function' (#36.28.32), line 3, column 1:
"cest"
Launch diagnostic report.
What is the reason for this and how can I work around this error in the best case?
(The problem: I am working on a project where exactly this error occurs when trying to include a Matlab script that calls several other scripts where this type of assignment occurs and Simulink gives the error even in scripts that are not directly included in Simulink).
Thanks!

Answers (1)

e=7
b(e);
function a = b(t)
cest = struct('d', 0, 'e', 0);
cest.d=t;
cest.e=cest.d;
a=cest.e;
end

3 Comments

Hello and thank you for the quick reply,
I think I have expressed myself a bit badly. I know that it could be solved this way, but it would mean that I would have to change a lot of scripts.
So maybe a more general question. Is it possible that Simulink passes values to Matlab scripts which in turn run in the Matlab environment and only the resulting values are passed back to the Simulink model? Because I had to find out that many other things do not work when I include Matlab scripts apart from the above mentioned struct problem. Why do some runnable Matlab scripts not work in Simulink?
Thanks!
Interpreted MATLAB Block
Note that this can only be used when acceleration is turned off, or is at the lowest possible acceleration. The higher acceleration steps are intended to generate to an environment in which the MATLAB runtime is no longer available.
If you need acceleration together with MATLAB functions, then you will need to sanitize the MATLAB functions.

Sign in to comment.

Products

Release

R2021a

Asked:

on 21 Aug 2021

Commented:

on 4 May 2023

Community Treasure Hunt

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

Start Hunting!