Unused Variable in Function

26 views (last 30 days)
Alex Triq
Alex Triq on 10 Mar 2022
Commented: Steven Lord on 10 Mar 2022
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

Answers (1)

Walter Roberson
Walter Roberson on 10 Mar 2022
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 Comments
Steven Lord
Steven Lord on 10 Mar 2022
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!