3

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?

4

1 回答 1

3

First of all, I must point out that surface is 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: load is a function that loads data from MAT files into the workspace. It is not fit for m-files. By not executing "exportedata.m" properly, surface has never been 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 the file with the filename stored in input, you can use run:

run(input)

By executing run(input) from within myfunction, surface should be created in myfunction'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:

function output = myfunction(input)
   surface = 0;                     %// <-- Pay attention to this line
   run(input);
   n = size(surface.vertices);

Predefining surface allows the interpreter to identify it as a variable throughout your entire function. I've tried it and it works.

于 2013-01-28T11:23:25.407 回答