- global variables
- shared variables with nested functions
- handle objects
- assignin() is used
Unused Variable in Function
조회 수: 27 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
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:
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
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 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 Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!