Check if a variable exists in the workspace, within a function

90 次查看(过去 30 天)
Hi,
I have a function which needs to check if a variable ('error_N') exists in the work space. If it does not exist, the function must create it.
In the following example, the function does not see the variable 'error_N' from the workspace. I tried to solve it by declaring it as a global variable. However, in the case the variable does not exist in the Workspace, Matlab creates an EMPTY variable called 'error_N' when reading "global error_N", so the function cannot create it with the value that I would like it to get.
Do you have any suggestions?
Thanks!
function output = function_example(input)
% global error_N ???????
E_1 = exist('error_N','var');
if E_1 ==1
else
error_N = 0.001;
end
output = function2(input);
error = output/N;
while error>error_N
blablabla
output....blablabla
end
end
  4 个评论
Stephen23
Stephen23 2019-3-29
Introspective programming (such as checking for the existence of variables) is slow and leads to complex code. The MATLAB documentation recommends to avoid doing this:
Better to simply use nested functions, known variable names, and explicit logic that keeps track of what data you have.
Walter Roberson
Walter Roberson 2019-3-29
The path you have defined so far is:
if variable exists in caller
do nothing in current workspace
else
create variable in current workspace
end
but in the path you defined, you do not pull out the variable from the caller.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2019-3-29
编辑:Walter Roberson 2019-3-29
if evalin('caller', 'exist(''error_N'',''var'')')
error_N = evalin('caller', 'error_N');
else
error_N = 0.001;
end
This would not be recommended. Better would be something like,
function output = function_example(x, error_N)
if ~exist('error_N', 'var') || isempty(error_N)
error_N = 0.001;
end
end
That is, the user passes error_N to you if the user wants something other than the default.
  4 个评论
Hisham Abbassy
Hisham Abbassy 2019-12-12
I'm trying to use it for GUI and it doesn't read the variable in the loaded mat file.
I also tried to use VarLoad but it doesn't work because I get error when the variable doesn't exist in my mat file.
Do you have an idea how to solve that?

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by