How do I get a main function to recognize all variables in a function?

I am stuck on this problem. How do I get the main function to display d?
function main(d)
a=1
b=2
disp(d)
function Math1
c=a+b
end
function Math2
d=c+2
end
end

4 Comments

What is your goal? Because your two nested functions are not used, nor a and b. The line below would display d.
d=0.5;main(d)
my goal is to modify the original function so it displays the answer to d.
RETURN THE VALUE d!!!!!!!
function d = Math2(c)
Then use it like a function inside Main.
d = Math2(c);
You need to learn to use functions.
@Brian Rreid: how to call functions is explained in the introductory tutorials:
How to define functions with output arguments is shown in the function help.
"How do I get a main function to recognize all variables in a function?"
In general that would be a very bad way to write code. Functions have independent workspaces, and that is how they are supposed to be. Trying to pass all variables from one workspace to another will be slow, complex, and buggy. The recommended way to write code is to pass the variables that you need.

Sign in to comment.

Answers (0)

Asked:

on 25 Apr 2018

Edited:

on 25 Apr 2018

Community Treasure Hunt

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

Start Hunting!