How can we call a variable defined in a function file to another script file?
이전 댓글 표시
I want to call a variable that is defined in a function file to another script file. In a naive way, I assigned this variable as an output of the function, however, this did not help me. That is, MATLAB still returns an error that the variable is not defined. Then, I realized that this may be because the output variable I am defining does not depend on the input variables of the function. (I do not know whether my realization is correct or not.)
Thus, I want to call a variable in a script file that is defined in another function file. Please help me how can I do this?
Thank you.
댓글 수: 14
@vikas mishra: how are you calling the function? Most likely you did not allocate the output argument to any variable when the function was called.
PS: Do not use globals or assignin. Passing the argument is the simplest way to do this. You just need to show us how you call the function.
vikas mishra
2017년 12월 11일
vikas mishra
2017년 12월 11일
Guillaume
2017년 12월 11일
Defining r = 0.25 in your script is the right thing to do. Now if you want to use that r in your functions, it's very simple. Just pass it as an argument to your functions.
import (or export) is not the correct term.
@vikas Mishra: how to call functions with input/output arguments is explained well in the introductory tutorials (which are highly recommended for all beginners):
The simplest, fastest, neatest solution is to pass that value as an input argument to the two functions. Why don't you just do this?
vikas mishra
2017년 12월 11일
편집: Stephen23
2017년 12월 11일
"I can not do it because my function has already some inputs..."
fsolve only provides one input argument x to the provided function. What do you the rest of the arguments do? How do you call the function using fsolve without getting an error?
"...and if I increase one more input by 'r', then when I call this function using MATLAB function 'fsolve' in the script file it will have more arguments than that needed by 'fsolve'"
Not true. You can easily add any number of input arguments to the function, and still call it with fsolve (or any other optimization routine). Do not use globals. Search this forum to know why.
"I can not do it because my function has already some inputs and if I increase one more input by 'r', then when I call this function using MATLAB function 'fsolve' in the script file it will have more arguments than that needed by 'fsolve'"
Not true. You can easily add any number of input arguments to the function, and still call it with fsolve (or any other optimization routine), by defining an anonymous function as required. Alternatively you could use nested functions. These are both explained quite well in the MATLAB documentation:
vikas mishra
2017년 12월 11일
vikas mishra
2017년 12월 12일
@vikas mishra: there is no single answer, because it depends on the kind of data that you have (you gave no details of this), how many data there are (you gave no details of this), how they are arranged (ditto), etc. The simplest solution would be to create a data file that suits your data and then read it using one of the standard file reading functions:
vikas mishra
2017년 12월 17일
erick oibi
2018년 5월 10일
@stephen Hey , I have a question, how do you initialize a variable in a script to a value obtained from a function. I have obtained power loss in the loadflow function. I want to initialize the base power loss in a script to the value obtained from the power loss, how should I go about.Kindly help.
dpb
2018년 5월 11일
Since a script is global scope, simply using the variable name as the LHS in the statement that calls the function will do so in the script which would be the "clean" way; then everything is within the script itself.
답변 (1개)
dpb
2017년 12월 2일
Well, you had the right idea; you didn't show us the syntax used but you must refer to the variable that is returned from the function to use it elsewhere; variables are local within functions so what they're called there is totally immaterial to what you use externally.
function returnVar=YourFunction(inputVar)
% do something here
...
returnVar=theResultofThatSomething; % set the returned variable in the function
Your script wanting to compute and use whatever it is YourFunction does looks like--
% whatever else goes on before in the script here
...
x=32.4; % some arbitrary initial value
y=YourFunction(x); % compute the result with that input
% Now y has the result from the function in the script
...
% Do whatever is needed/wanted with y here...
...
댓글 수: 6
vikas mishra
2017년 12월 2일
It doesn't matter what is done in the function nor what it is/is not dependent upon...unless the function returns the value of interest, you can't see it from outside the function.
If it does return what you're interested in, then the above code structure with whatever is the proper syntax to call it is how to structure your script.
If, otoh, it doesn't return the value or it is some intermediary values inside the function that you're actually interested in (I can't tell precisely from the description, actual pertinent code would be better), then you'll have to either modify the function to provide what you're looking for as output(s) or pick up that portion of that code and replicate it in the script.
There's the [proverbial-appendage here]-ugly alternative of global but that is to be avoided at extreme unless there simply is no other way.
The last alternative (but that may be the one here) also requires a modification to the function that makes it then pretty-much only suitable for the specific purpose and that would be assignin.
See
doc assignin % for details
By its use in the function, you can force a given variable to be stored into the caller's or the base workspace rather than using a return variable. This again is not a practice to fall in love with; it breaks code modularity and is fraught with multiple ways to wreak havoc including writing over other variables of the same name that might exist in the target space but that aren't actually related.
vikas mishra
2017년 12월 3일
편집: dpb
2017년 12월 3일
You don't show the calling code where the error would occur, though. As written, theta_0 is the second argument returned so your calling syntax would have to have explicitly allowed a place for it; only the first argument is ever returned "automgaically".
But, as the function is written, having theta_0 as a dummy variable in the argument list is pointless--it's overwritten by hardcoded value of the for loop, anyway.
Also, NOTA BENE: theta_0 on return from the function will always be the one constant value equal to deg2rad(21) since it's the loop variable and only takes on the loop values one-at-a-time as the loop executes. When the loop is done and the function returns, it's only the last loop that executed for which there is a theta_0 defined.
vikas mishra
2017년 12월 3일
BAD IDEA!!! DO NOT use GLOBAL here; it's bad design and will lead to continuing such with time.
Fix the logic as outlined previously--there's no reason if the theta_0 range is to be hardcoded for it to be buried in the function; that makes the function of little generic value; instead write the function generically and then you can call it with a desired range from the caller and the problem of finding out the values within the function goes away entirely.
function p=whiskerShapeLoop_res(IC_guess, theta_0)
xcf=14.87;
ycf=4.71;
r=0.25;
for theta=deg2rad(theta_0)
[x,y] = ode45(@whiskerShape_model, [0 1],[0 0 theta IC_guess(1) IC_guess(2) IC_guess(3) 0]);
p = [y(end,1)-(xcf+r*sin(y(end,5))), y(end,2)-(ycf-r*cos(y(end,5))), y(end,3)-y(end,5)];
...
and in the script use
theta_0=0:10:21;
or even better would be something like--
dtheta=10; % set incremental theta
thethaUp=21; % upper limit for theta
theta_0=[0:dtheta:thetaUp]; % set the range
p=whiskerShapeLoop_res(IC_guess,theta); % call the routine
...
This way you have a much more flexible toolset that can be utilized for any range of inputs that comes up; not just the one specific one simply by modifying the constants. Or, of course, generalize even further by reading the constants or getting them from the user on the fly so don't have to make any code changes to run different cases.
NB: Of course, this still doesn't solve the problem that the loop inside the function is pointless--you don't return anything except the result after the loop is completed; all the intermediary results are calculated by "thrown away" by the reassignment of each result into the same variable, p.
It's not clear what you're really after for certain, but if it is the result for each element of the vector of starting conditions, then you'll need to save that as an array in the function.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!