I have observed a strange behavior in running the same code in a Matlab function and in the command window. It’s already described in How does scoping in Matlab work? , but I don’t understand how I could solve my specific problem.
The code is the following:
exporteddata.m %File created by an external program
%to export data in Matlab format
surface = struct('vertices', [...]) ;
%I can't specify in the external program
%the name of the variable, it's always "surface"
My actual code is:
myfunction.m
function output = myfunction(input)
load(input);
n = size(surface.vertices);
....
When running
myfunction('exporteddata.m');
I get the following error:
??? No appropriate method, property, or field vertices for class hg.surface.
When running the same instructions from the command window or in debug mode, the code works well.
How can I specify in the function that I need the variable surface present in the workspace, not the Matlab function?
First of all, I must point out that
surfaceis a built-in function in MATLAB, so overloading it is just… bad. Bad, bad, BAD!Having said that, the MATLAB interpreter does a pretty good job at resolving variable names and usually tells them apart from function names correctly. So where’s your problem, you ask?
I believe that you’re using the wrong function:
loadis a function that loads data from MAT files into the workspace. It is not fit for m-files. By not executing “exportedata.m” properly,surfacehas never been created as a variable, so MATLAB identifies it as a function name. If you want to execute “exportedata.m”, just type:and if you want to run the file with the filename stored in
input, you can userun:By executing
run(input)from withinmyfunction,surfaceshould be created inmyfunction‘s local scope, and it should work.EDIT:
I’ve just tested it, and the interpreter still gets confused. so the issue of the variable name resolution remains. Here’s a workaround:
Predefining
surfaceallows the interpreter to identify it as a variable throughout your entire function. I’ve tried it and it works.