call a function from another function with one changing argument
1 次查看(过去 30 天)
显示 更早的评论
I have a function
function dos= beam(x)
This function calculates certain parameters such as "moment", "stress" etc. I have another function
function[c ce]=constraint(x,dos)
This function requires some parameters calculated in the first function such as "moment". The value of x must be same for both the functions. x is chosen randomly from a given defined set.for example
allx1_2=[1, 2 ,5 8 , 9 ,10];
I want that whatever the value is taken from the set for running the first function , the same value be passed to the second function. Both functions need to be in different scripts ( cannot be used in same script). I just need to know how will I provide function handles or any other way??
0 个评论
回答(2 个)
Walter Roberson
2015-5-4
thisx = allx1_2(randperm(length(allx1_2),1); %select a random x
r1 = beam(thisx);
[r2, r3] = constraint(thisx, r1);
Stephen23
2015-5-4
编辑:Stephen23
2015-5-4
The easiest, neatest and most bug-free way of passing values is to ... pass variables!
Although beginners seem to love writing scripts, learn to write functions rather than scripts and then passing variables is easy to write, easy to debug and easy to follow the information flow with. Functions also have many other advantages including their own workspaces, and nice things like that.
MATLAB themselves have documented how to pass values between workspaces, the preferred method is to pass variables:
It can be as easy as creating a meta-function that calls several other functions, and then your entire question can be resolved by something like this:
function my_meta_fun(x)
dos = beam(x);
[c,ce] = constraint(x,dos);
... other code
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!