MATLAB Answers

Have function use variables within workspace

23 views (last 30 days)
Adam Levschuk
Adam Levschuk on 27 Feb 2021
Commented: Walter Roberson on 28 Feb 2021
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
Adam Levschuk
Adam Levschuk on 28 Feb 2021
hi walter , thank you for your help.
I call the function at the very end of the script (once all my varaibles are already calculated). However, my function at the end that is supposed to put all my variables in a convient txt file cannot find the variables that were just calculated and were now in the workspace.

Sign in to comment.

Answers (1)

Walter Roberson
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
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by