How do I declare a variable in the MATLAB workspace from a MATLAB function?

29 views (last 30 days)
I wrote a function that provides some variables to Simulink. I have declared them global, so Simulink could see them. But I have to declare them at the prompt and I am unable to declare them in the function because Simulink does not see them.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 10 Dec 2021
Edited: MathWorks Support Team on 13 Dec 2021
Simulink has access to any variable defined in the MATLAB workspace. You do not need to declare a variable 'global'. In order to define a variable in the MATLAB workspace from a function, you can declare the variables in the function using the command EVALIN. For example:
function declare_variable
In this example, when the function 'declare_variable' is called, it will generate a variable 'k' in the MATLAB workspace. This variable can then be seen by the Simulink model. Please note that if, before the function 'declare_variable' is called, a variable called 'k' exists in the MATLAB workspace already, calling the function 'declare_variable' will overwrite the existing variable 'k' with the new value (100).
For more information on the EVALIN function, see the following URL:
  1 Comment
fabrizio on 7 Jun 2016
Hi, how can i pass the new value as a function like:
I am trying to use the simulink model output as a fitness function for GA.
Thank you

Sign in to comment.

More Answers (1)

Gaganjyoti Baishya
Gaganjyoti Baishya on 20 Jun 2020
You can easily add variables in base from function using assignin.
function myFunc(a,b)
assignin declares the varibale myVar with value of 3.


Find more on Scope Variables and Generate Names 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!