Hello,
I provide a specific solution at the bottom after the explanation on global variables.
Global variables are a way to have variables accessible across multiple functions!
Try this:
function a = fcn1()
a = 5;
b = 6;
fcn2()
end
function a = fcn2()
a = b;
end
Notice that it gives you an error because "b" is an undefined function or variable.
This is because the variable "b" was a variable that only existed in function fcn1(). It was a local variable, and its scope was only within fcn1(). If you want variables to have a global scope, so that they can be accessed anywhere, you can declare them as global variables.
This is how you can declare a and b as global variables:
Now try this:
function a = fcn1()
global b
a = 5;
b = 6;
fcn2()
end
function a = fcn2()
global b
a = b;
end
It should run smoothly, and fcn2 will output a = 6. This is because b is a global variable accessible everywhere it has been declared. Further and more detailed information on global variables can be found here. It's important to note that you must write
global var1 var2 var3 etc
in each function that you wish to have access to these global variables.
With respect to your function, it has improper syntax, it should look something like this:
function outputs = function_name(inputs)
In your case, the following code might provide the solution you were seeking, please read carefully over it to understand how the global allows the variables to be accessed even though they weren't passed into the function as inputs:
function plot_dif_h_values()
global x h
figure(1)
hold on
x = linspace(0.1,2);
hvec = [0.015625, 0.1, 0.5];
for i = 1:3
h = hvec(i);
fx = myF();
plot(x,fx)
end
end
function fx = myF()
global x h
fx = 1./(((1-x.^2).^2+h.*x.^2).^(1/2));
end
I'm not exactly sure what you're looking for, but the above code is how I interpreted your question. Please ask any questions or correct me if I misinterpreted the question!
Hope this helps!
Best Answer