MATLAB: Constants and Matlab Workspace

MATLABworkspace

Say I have defined X1 = 20 in a script file and ran the script file. So my Workspace has X1=20.
I open up Simulink and create a model where I create a condition. I compare a new variable X2 (X2 = 40) to X1 in Simulink, and if X2 > X1, then set X1 = 40. I noticed that X1 appears to change to 40 in Simulink but not in the Workspace. Why is that?
So what is the actual value of X1 in Matlab? is it 20 or 40 then? or maybe Im not doing something correctly here?

Best Answer

The MATLAB has several different workspaces. Simulink model has its own workspace: https://www.mathworks.com/help/simulink/ug/using-model-workspaces.html. The workspace you see on the main MATLAB window is called the base workspace. The method to change a variable in base workspace depends on what you are trying to do. One way is to use the To Workspace block: https://www.mathworks.com/help/simulink/slref/toworkspace.html. The other is to use evalin and assignin functions, as shown in the attached file. To run this model, define a variable x in the base workspace by running
x = 5
Then run the model. In the Simulink model, there is a MATLAB function block, which increments the value of x at each time instant. However, note that using evalin and assignin is not a recommended practice, and they can make the model run very slow. If possible, try using the To Workspace block as it will not result in slow performance.