Unused Variable in Function

26 次查看(过去 30 天)
Alex Triq
Alex Triq 2022-3-10
So I hve this small snippet of a function, and whenever I try to run it, it does not show any variables in the workspace. Also, it keeps giving me the warning that there are some unused variables, which I do not know why. I would like the val and sum values to be displayed in the Workspace, but it does not seem to work. The function does not have any output values but one input variable, val.
function calculator(val)
if (val > 23 && val < 100)
if (val < 50)
sum = val + 5; % Warning here
val = val - 1; % Warning here
else
val = 99; % Warning here
end
end

回答(1 个)

Walter Roberson
Walter Roberson 2022-3-10
it does not show any variables in the workspace.
Values assigned to inside a function disappear as soon as the function returns, with the following exceptions:
  • global variables
  • shared variables with nested functions
  • handle objects
  • assignin() is used
If you need sum to show up in the workspace, then you need to stop execution inside the function, or you need the function to specifically write the values into the base workspace (which is not recommended.)
function calculator(val)
if (val > 23 && val < 100)
if (val < 50)
sum = val + 5;
val = val - 1;
display(sum)
display(val)
else
val = 99;
display(val)
end
end
  2 个评论
Steven Lord
Steven Lord 2022-3-10
You forgot the most common way variables get out of a function: by being returned as output arguments.
[valOutput, thesumOutput] = calculator(30)
valOutput = 29
thesumOutput = 35
valOutput contains the contents of the variable val at the time the calculator function finished executing, and similarly for thesumOutput and thesum.
function [val, thesum] = calculator(val)
if (val > 23 && val < 100)
if (val < 50)
thesum = val + 5; % Don't use sum as a variable name
val = val - 1; % Warning here
else
val = 99; % Warning here
end
end
end
Your code still has at least one bug even if you add the output arguments to the signature and call the function with outputs, though. I'll leave it to you to find.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by