MATLAB Answers


How do I run a script from a GUI that will run in the 'base' workspace?

Asked by John Petersen on 25 Feb 2016
Latest activity Commented on by Sanjeev Kumar on 26 Feb 2019
I have a simulink model that uses a lot of variables from the base workspace. Now I am making a GUI that runs the model, but I want to be able to reinitialize the base workspace by calling the script that does this. But I want to do it from the GUI. How do I run a script as if in the base workspace so that it populates all the variables there? I could use assignin('base', var, reinitvar), but this would be extremely tedious for all the variables. Is there another option?


Why would you want variables in the base workspace when you are working in a GUI? A GUI has its own 'workspace', or rather it has a workspace for each callback you program, but each of those workspaces can have access to the same GUI data, either using the handles struct to store it or methods like setappdata, getappdata.
Adam has asked the most important question. Making variables magically appear (or evalin-ing) in workspaces is buggy and slow. So why do this? Keep workspaces distinct, and pass variables properly.
It is because Simulink "From Workspace" blocks get their values from the Base workspace if the model is invoked by double-clicking on it or by using the menus. However, if the model is invoked by a MATLAB function running the sim() command, then From Workspace gets its variables from the workspace of the function that has the sim() call. I gather, however, that it is not uncommon for From Workspace blocks to somehow be configured to look only in the Base workspace.
Simulink bypasses normal workspace encapsulation sometimes :(

Sign in to comment.

2 Answers

Answer by Walter Roberson
on 25 Feb 2016
 Accepted Answer

evalin('base', 'name_of_script')


Thanks a lot, saved a lot of effort. I am a beginner in MATLAB and these different workspaces was causing a lot of confusion when i was trying to pass values in SIMULINK using "From-Workspace" block
But its not working while using the same command in Callback function of a button in Matlab GUIDE.
function Button_callback(hObject,eventdata,handles)
An error is coming like:Undefined variable 'MyScript.m' or class 'MyScript.m'

Sign in to comment.

Answer by pjman yucifee on 10 Apr 2018

Very nice.....Thanks a lot


Sign in to comment.