MATLAB: How to load a file in a function

filefunctionloadMATLAB

Hello,
I've recently started learning MATLAB, so forgive me if my question and code are both ridiculously stupid.
I'm attempting to write a function that, amongst other things, loads a file from the currently directory into the workspace in order to use the data in this file for other parts of the function.
Currently, the code looks like this:
function [] = tubeguide ()
load ('hamm_and_city');
end
'tubeguide' is the function name, and 'hamm_and_city' is the file I'm attempting to load, but currently, nothing loads into the workspace.
Thanks.

Best Answer

"'tubeguide' is the function name, and 'hamm_and_city' is the file I'm attempting to load, but currently, nothing loads into the workspace."
I suspect that your confusion is related to "the workspace" : in fact every function has its own independent workspace, and this is NOT the base workspace (i.e. where you normally work from the command line, and can see lots of nice variables in the Variable Viewer). Every function should have its own workspace, because that is the entire point of functions.
Variables exist in a function workspace for as long as the function is being run, and then when it ends all of the variables in it are discarded (unless they are otherwise passed as an output argument or as arguments to another function, etc.). Judging by your function you load your data into the function workspace, do nothing with it, and then throw it away.
If you want to get those variables in the base workspace, then the easiest and most reliable way is to pass them as output arguments:
function S = tubeguide()
S = load('hamm_and_city.mat');
end
And then use an output variable when you call that function:
out = tubeguide()
Related Question