How to set the scope of a variable in a Matlab function
I have observed strange behavior when running the same code in Matlab function and command window. This is already covered in How does scoping work in Matlab? but I don't understand how I could solve my specific problem. The code is as follows:
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 always "surface"
My actual code:
myfunction.m
function output = myfunction(input)
load(input);
n = size(surface.vertices);
....
At startup
myfunction('exporteddata.m');
I am getting the following error:
??? There are no suitable methods, properties or field tops for the hg.surface class.
When executing the same instructions from the command window or in debug mode, the code works well.
How can I indicate in a function that I want a variable surface present in the workspace and not a Matlab function?
source to share
First of all, I have to point out what surface
is a built-in function in MATLAB, so the overloading is just .... Bad. Bad, bad, BAD !
Having said that, the MATLAB interpreter does a pretty good job of resolving variable names and usually correctly describes them separately from function names. So where is your problem, you ask?
I believe you are using the wrong function: load
is the function that loads data from MAT files into the workspace. It doesn't fit m files. Without executing "exportedata.m" correctly, it was surface
never created as a variable, so MATLAB identifies it as a function name. If you want to execute "exportedata.m" just type:
exportedata
and if you want to run a file with the filename stored in input
you can use run
:
run(input)
Carrying out run(input)
of myfunction
, surface
it should be created in the local area myfunction
, and it should work.
EDIT:
I just tested it and the interpreter is still confusing. so the problem of resolving variable names remains. Here's a workaround:
function output = myfunction(input)
surface = 0; %// <-- Pay attention to this line
run(input);
n = size(surface.vertices);
Predefinition surface
allows the interpreter to identify it as a variable throughout your entire function. I tried it and it works.
source to share