call a function from another function with one changing argument

2 views (last 30 days)
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??

Answers (2)

Walter Roberson
Walter Roberson on 4 May 2015
thisx = allx1_2(randperm(length(allx1_2),1); %select a random x
r1 = beam(thisx);
[r2, r3] = constraint(thisx, r1);
  1 Comment
Ace_ventura
Ace_ventura on 4 May 2015
Edited: Ace_ventura on 4 May 2015
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.

Sign in to comment.


Stephen23
Stephen23 on 4 May 2015
Edited: Stephen23 on 4 May 2015
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

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!