Have function use variables within workspace
6 views (last 30 days)
Show older comments
Hello, i am new to creating functions.
I am creating a function that creates a text file that conviently writes out all of my results for me. I have made function that does this and palced it at the end of my code. However, when i run the script with the fucntion in it i get a message saying "unrecognzied function or variable". This is confusuing becuase the variable that it is calling unrecognzied is right in my workspace? why is the function not recognziing the variable?
2 Comments
Walter Roberson
on 28 Feb 2021
We would need to see more to advise.
Generally speaking, if you assign to a variable inside a function, then the variable disappears as soon as the function returns, unless you pass the value out of the function.
function y = f(x)
s = std(x); %this variable will be lost
y = x - s.*x; %this variable can be captured on output
end
Answers (1)
Walter Roberson
on 28 Feb 2021
Normal functions cannot see the variables in the workspace of the caller -- not unless the function specifically asks to look there (which, in most cases, is Not A Good Idea.) You need to pass the values into the function.
There is an alternative: you can define a nested function, and that can see variables in the workspace of the caller that were initialized before the definition of the nested function. For example,
function outer
visible = 123;
function result = inner
result = visible + invisible;
end
invisible = 456;
y = inner();
end
In this case, inner can see visible because it was assigned to in outer before the function inner was defined, but inner cannot see invisible which was assigned to after inner was defined -- and this rule holds even though invisible is assigned to in outer before inner is called
2 Comments
Walter Roberson
on 28 Feb 2021
If this is for a homework assignment, I would recommend using parameters.
If it is not a homework assignment, then I might use a nested function if it is a one-time thing. However if the same functionality is going to need to be called elsewhere, then using a nested function is not appropriate.
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!