How can I refer to a variable, defined in one .m file, within a function defined in another?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I define a mixed cell in KSP_run.m:
%%Define celestial body characteristics and scientific constants
%Body Eq. Radius Mass R. Period SOI
bodies = {'The Sun' 2.616e+08 1.757e+28 4.32e+05 Inf ;
'Moho' 2.5e+05 1.757e+28 4.32e+05 9.647e+06 ;
'Eve' 7e+05 1.224e+23 8.046e+04 8.5109e+07 ;
'Gilly' 1.3e+04 1.242e+17 2.82e+04 1.26e+05 ;
'Kerbin' 6e+05 5.292e+22 2.1549e+04 8.4159e+07 ;
'Mun' 2e+05 9.76e+20 1.3896e+05 2.43e+06 ;
'Minmus' 6e+04 2.646e+19 4.038e+04 2.247e+06 ;
'Duna' 3.2e+05 4.515e+21 6.546e+04 4.7922e+07 ;
'Ike' 1.3e+05 2.782+20 6.546e+04 1.05e+06 ;
'Dres' 1.38e+05 3.219e+20 3.48e+04 3.2833e+07 ;
'Jool' 6e+06 4.233e+24 3.6e+04 2.445985e+09 ;
'Laythe' 5e+05 2.94e+22 5.298e+04 3.724e+06 ;
'Vall' 3e+05 3.109e+21 1.0596e+05 2.306e+06 ;
'Tylo' 6e+05 4.233e+22 2.1192e+05 1.0857e+07 ;
'Bop' 6.5e+04 3.726e+19 5.445e+05 1.221e+06 ;
'Pol' 4.4e+04 1.081e+19 9.0186e+05 1.042e+06 ;
'Eeloo' 2.1e+05 1.115e+21 1.946e+04 1.19083e+08 };
G = 6.6741e-11;
I define the function KSP_bod in KSP_bod.m:
%%Pick a celestial body and define its parameters.
function [R,M,T,SOI] = KSP_bod()
body = input('Please enter a celestial body to focus on: ','s');
row = find(strcmp(bodies,body));
R = bodies(row,2);
M = bodies(row,3);
T = bodies(row,4);
SOI = bodies(row,5);
end
KSP_bod.m is called immediately after bodies and G are defined in KSP_run.m:
[R,M,T,SOI] = KSP_bod();
It seems that KSP_bod.m does not recognise the existence of bodies.The following issue occurs:
Undefined function or variable 'bodies'.
Error in *KSP_run* (line 3)
row = find(strcmp(bodies,body));
Error in *KSP_run* (line 24)
[R,M,T,SOI] = KSP_bod();
I believe the issue is scope-related but do not know how to fix it. Referring to bodies outside of KSP_bod.m (e.g. by typing:
bodies
into the command window) works perfectly fine.
0 commentaires
Réponse acceptée
Fangjun Jiang
le 13 Août 2018
Define it as an input argument and pass the value in
function [R,M,T,SOI] = KSP_bod(bodies)
call using the syntax
[R,M,T,SOI] = KSP_bod(bodies)
4 commentaires
Stephen23
le 13 Août 2018
Modifié(e) : Stephen23
le 13 Août 2018
"the variables R, M, T, SOI are now 1x1 cells. Is this different from a simple number, such as G?"
Yes: cell arrays are a container variable, which can contain other arrays.
"Is there a way to be able to just type 'KSP_bod' into the command window and have it work, or is this the only solution to my issue?"
There are always other ways of doing things... But passing values as input/output arguments, as Fangjun Jiang showed you, is by far the simplest and most efficient way of getting data out of a function.
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!