MATLAB Answers

Utilize variable from different function

조회 수: 3(최근 30일)
Simon Blasko
Simon Blasko 2 Jan 2021
댓글: Cris LaPierre 3 Jan 2021
I have one function (Golf_Projectile_DragMagnus) which outputs the final distance reached by a golf ball with varying factors that affect the distance if ran numeruous times. And the function below which is meant to find the mean distance reached after multiple iterations. Since the answer for the first function is always different I need to run it each time before it adds to the Total. The output of my first function is only the scalar of distance reached.
function Golf_Projectile_mean
N_Iterations = 1000;
Total = 0;
for i=N_Iterations
Total = Total + FinalImpact;
Mean = Total/N_Iterations;
I have tried to make the variable FinalImpact global in the Golf_Projectile_DragMagnus function however that does not seem to work. Thank you for your response in advance.


Cris LaPierre
Cris LaPierre 2 Jan 2021
Function each have their own workspace. The proper way to return a variable from a function is through the function output variable. See more here.
  댓글 수: 2
Cris LaPierre
Cris LaPierre 3 Jan 2021
You would have to set the output variable of your function equal to whatever you wnat to return. Your original function did not have an output variable.
Borrowing an example from the page I sent you to before, let's say I have a function that accepts an array of input values and returns the average. When I declare the function (first line), I specify what the output (ave) and input (x) variables are.
Then, when I call the function in another script or function, I assign the output the function returns to a variable. I can then use that variable in my code.
z = 1:99;
% Call function and assign output to a variable (myAve)
myAve = average(z)
myAve = 50
% I can now use the ouput here
newVar = myAve/10
newVar = 5
% Function input is x, output is ave
function ave = average(x)
% assign output to output variable ave
ave = sum(x(:))/numel(x);

댓글을 달려면 로그인하십시오.


Community Treasure Hunt

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

Start Hunting!

Translated by