How to load a file in a function

27 views (last 30 days)
James Hill
James Hill on 28 Dec 2018
Commented: madhan ravi on 11 Jan 2019
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.

Accepted Answer

Stephen23
Stephen23 on 28 Dec 2018
Edited: Stephen23 on 28 Dec 2018
"'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()

More Answers (1)

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!