Konstantin
Konstantin

Reputation: 431

Matlab function working only in debug mode

I have a function in a separate file

   function [ ] = loadModel( model , version )

   cd(model.path);  

   loadPath =  strcat(model.name(1,:) , model.versions(version,:), '_results' ) ;

   load(loadPath,'-mat');

   end

which using model structure and version number as inputs changes directory to the one of the model and loads its results. When I call the function from a m-file there is no error but its seems like none of the lines of the function have been executed e.g. a variable loadPath doesn't even exist. When I put a break point before load(), I see loadPath generated correctly and if I type the last line manually it works fine. Any clues why is this happening?

P.S. I am used to C++, Java and I find the matlab language absolute nighmare

Upvotes: 1

Views: 577

Answers (2)

am304
am304

Reputation: 13876

You need to understand the concept of workspace: the function workspace is different from the base workspace (the one you can access from the command line). Your function executes normally and the variable loadPath is created, but in the function workspace, not the base workspace. As your function doesn't return anything you don't have access to it. In debug mode, you get access to the function workspace, so you can see the variable. You need the function to return the variable of interest if you want to access it from the base workspace. I suggest you have a look at the documentation, it's very thorough.

Upvotes: 1

MrAzzaman
MrAzzaman

Reputation: 4768

This is because you're only loading the file within the scope of the loadModel function. In MATLAB, variables declared within a function (this includes through file loading) are only defined within that function (barring global variables, assignin, etc). You need to return the results of the file load in order to use the loaded data. For instance:

function data = loadModel( model , version )

cd(model.path);  

loadPath =  strcat(model.name(1,:) , model.versions(version,:), '_results' ) ;

data = load(loadPath,'-mat');

end

This will load the file into a struct, which is returned to the calling scope. You can then access the loaded data from this struct.

Upvotes: 2

Related Questions