Matlab confusion of function and variable names after load

44 ビュー (過去 30 日間)
NMTri
NMTri 2018 年 2 月 1 日
編集済み: Stephen23 2018 年 2 月 1 日
Hi everyone. I encountered a strange problem about function and variable names. I tried this
clear all
close all
alpha=1;
save ('data1.mat')
test1
Where test1 is the function
function test1
load data1.mat % which contains only variable alpha
alpha % to see the value of alpha
And the error appeared, as if I called function alpha instead of variable alpha. As I know, when we name a variable same as a builtin function, matlab treats that name as a variable name whenever it is called (and we should avoid that style of naming).
Also, in my case, I used 'whos' command to see if there was a variable named 'alpha' in the workspace after load function. And I did have that 'alpha' variable. Just why this problem happened? All the functions, .mat file are in the same folder. I've tried in Matlab 2016a,b and 2017b.

採用された回答

James Tursa
James Tursa 2018 年 2 月 1 日
編集済み: James Tursa 2018 年 2 月 1 日
The load command 'poof'ed a variable into the function workspace after the parser had parsed the m-file and associated "alpha" with the function of that name. To avoid this confusion, load into a struct and extract your desired variable. E.g.,
s = load('data1.mat'); % which contains only variable alpha
alpha = s.alpha % to see the value of alpha
  2 件のコメント
NMTri
NMTri 2018 年 2 月 1 日
Yeah, thank you for your answer. I know we should avoid that. However, why 'whos' command showed that the variable 'alpha' was actually in the workspace (by adding whos after load command, we can see this). Is there anything in your answer that I don't understand? Can you explain clearer about the parsing process in this case. :)
Walter Roberson
Walter Roberson 2018 年 2 月 1 日
Adding whos after load() does not affect how the Just In Time compiler parses the function.
MATLAB has been getting stricter and stricter on this, and will be getting even more strict in the future -- for performance reasons.
Inside a function, if you call a script to define a variable, or if you load() with no output to define a variable, then you should no longer assume that MATLAB will understand afterwards that the name should be associated with the new value.
In the case of scripts, if there is any possibility of a conflict with a variable defined in the script, assign a value to that variable before the script is called.
In the case of load with no output argument, if there is any possibility of a conflict with a variable defined by load, assign a value to that variable before load is called. Or, better yet, change the load() to have an output argument and pull values out of the resulting struct().

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by