How to load a file in a function

29 ビュー (過去 30 日間)
James Hill
James Hill 2018 年 12 月 28 日
コメント済み: madhan ravi 2019 年 1 月 11 日
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.

採用された回答

Stephen23
Stephen23 2018 年 12 月 28 日
編集済み: Stephen23 2018 年 12 月 28 日
"'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()
  1 件のコメント
James Hill
James Hill 2019 年 1 月 11 日
Thank you!

サインインしてコメントする。

その他の回答 (1 件)

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by