I have been struggling with this problem for about a week. I have been trying to convert a script into a function for research purposes. The problem is that the code has a lot of conditional existing statements for variables, so certain variables won't exist in the workspace when they are checked for (this is why it works well as a script).
Varargin is not a solution to this problem because some of the function INPUTS won't exist.
Workspace
var1 = 1
var2 = 2
var4 = 4
Code to turn into function
if exist('var3','var')
disp('var 3 exists')
else
disp('var 3 does not exist')
end
The following function will NOT work because it is calling variable 3 which does not exist.
calling function
runCode(var1, var2, var3, var4)
I originally wrote this prior my function and made the code check for isnan
instead of exist
, but it's not great practice and since the function is called often, I don't want to have to update this function setup whenever changes to the code are made.
if ~exist("var1", "var"), var1= NaN; end
if ~exist("var2", "var"), var2= NaN; end
if ~exist("var3", "var"), var3= NaN; end
if ~exist("var4", "var"), var4= NaN; end
I don't want to use eval
, and loading the workspace has caused me issues because a bunch of figures are present and it messes up the figure count in a later portion of the code. The only ideas I have right know is have a setup script for the previous if statements, or somehow save all of the workspace data into a struct or something and then assign the values the corresponding who
string (gives workspace variable names).
Thanks for any ideas you guys might have