Unused Variable in Function

조회 수: 27 (최근 30일)
Alex Triq
Alex Triq 2022년 3월 10일
댓글: Steven Lord 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
Alex Triq
Alex Triq 2022년 3월 10일
Thank you
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