How to use a variable from a script in another script
Ältere Kommentare anzeigen
I am trying to write a script that demonstrates the methods of finding roots in graphs (regula falsi, bisection and newton raphson) and want to demonstrate the number of steps each one took at the end. Currently i am trying to do this by creating a variable of the number of steps at the end of the functions for example my for regula falsi:
function root = regula_falsi(a,b)
% implementation of the regula falsi method starting
% with x=a and x=b as the brackets
% check that the two points bracket the root
if(~(f(a)*f(b)<0.0))
disp('Root not bracketed!');
return;
end
% set the tolerance: how close to the root
% does the function have to be?
tol = 1.0e-9;
% keep count of the number of steps
step = 1;
while(abs(f(a))>tol && abs(f(b))>tol)
% print out for use
fprintf('step %d, a = %d, b = %d\n',step,a,b)
% find midpoint
m = a - (b-a)/(f(b)-f(a))*f(a);
% which are the new brackets?
if(~(f(a)*f(m)<0.0))
a=m;
else
b=m;
end
step = step + 1;
end
if a==m
fprintf('root is at %d',a)
else
fprintf('root is at %d',b)
end
c=step
however when i try to use the variable c in another script it is not defined so how could i change this so that the variable c is in my workspace
4 Kommentare
Star Strider
am 15 Mai 2019
First, step is the name of several MATLAB built-in functions. It would be better to use a different name, perhaps ‘steps’.
Second, you are not returning ‘c’ as one of your function outputs, so it will not be available outside your function. (You are also not defining ‘root’, unless I’m missing something in your code.)
Isaac Malceod
am 15 Mai 2019
Bob Thompson
am 15 Mai 2019
function c = regula_falsi(a,b)
Changing yoru function definition like this will return 'c' as your function output. You can also both root and c by placing [root,c] to the left of the equals.
If you want to share specific variables outside of a function, or between fuctions, not just as an output, then you can also define them as global variables.
Geoff Hayes
am 15 Mai 2019
Set your signature to include c as an output parameter
function [root, c] = regula_falsi(a,b)
Please make sure that you assign default values to root and c so that when exiting the function (or "returning" as you do if the two points fail to bracket the root) there is no error.
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Workspace Variables and MAT Files finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!