call a function from another function with one changing argument

2 次查看(过去 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??

回答(2 个)

Walter Roberson
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);
  1 个评论
Ace_ventura
Ace_ventura 2015-5-4
编辑:Ace_ventura 2015-5-4
Thank you Walter but this is how I have exactly defined my function.To be more clear to you , I have a third function defined as x=random(x). So overall , I have three functions defined in separate scripts.Now, any x value taken from random (x) function should be passed to beam(x) function in different script and then this beam(x) function would calculate "moment" . Then I have to pass same x value to third script constraint(x,dos) because I have to use same x value and the "moment value "calculated in the second function Function dos=beam(x)..Again, all three are in different scripts. I hope you understand what i am trying to ask. If there is any confusion please do ask:). I just want to know how to pass values.

请先登录,再进行评论。


Stephen23
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 CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by