In MATLAB, why is a variable that already exists in the workspace not recognized within a function, even when the function is located in the same directory?

45 views (last 30 days)
As shown in the figure, the variable Name was defined in advance and is present in the workspace. However, this variable was not recognized inside another function located in the same path, even though it was intended to be used as the figure title. Moreover, the variable Name was neither cleared nor overwritten during execution.

Accepted Answer

Walter Roberson
Walter Roberson on 25 Jan 2026 at 6:52
That is just how functions work.
Each function has its own "workspace" of variables. Inside a function, the only accessible variables are:
  • named parameters of the function
  • variables that have been defined inside the function by that point in the code
  • In the case of nested functions, variables that are defined by the nesting function before the nested function is defined
  • variables that have been explicitly defined as being global inside the function, in which case they share the value with all the other places that also declare the variable to be global
  • variables that have been created using assignin('function') by a called function
As well, it is possible to request access to variables that have been defined in the base workspace.
In this case, you have a script named procerod3_choi_shin that defines some variables. By default, variables defined in a script (that is not called by another function) are defined in the base workspace.
You then have procerod3_choi_shin call the function named plt_er1 and attempt to access a variable defined in procerod3_choi_shin . However, by the workspace of the function is searched, not the base workspace. The variable is defined in the base workspace, but the function does not search the base workspace by default.
You have two choices for this situation:
  1. You can pass Name into plt_er1 as an additional named parameter; or
  2. You can explicitly call Name = evalin('base', 'Name'); inside of plt_er1 in order to explicitly search the base workspace for the value of the variable.
There is a third choice:
Inside plt_er1 instead of calling title(Name) call title(titlestr) -- thus using the value of the named variable that you are already passing into plt_er1 .
You might need to adjust title(titlestr) a little. You should use the same variable name that you declared as the fifth parameter inside plt_er1
function plt_er1(FirstParameterName, SecondParamterName, ThirdParameterName, FourthParameterName, ParameterNameToReceivetitlestrInto)

More Answers (0)

Categories

Find more on Entering Commands in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!