How can I evaluate a function that is a function of other functions but all relate to the same parameter such as x

I have a bunch of functions that are related to each other through one parameter which is in my case altitude. I am having trouble understanding how MATlab is interpreting what I am writing.
func1=@(x) Some_Constant*x^2
func2=Some_Other_Constant*func1(x)
func3=Yet_Another_Constant*func2*func1
I would like to plot func3 vs x, how is Matlab interpreting what I wrote above and what is the right way to write the above code? Is there a good help page to answer my question? I have not been able to find one thus far.

Answers (1)

Just write it like any other Matlab expression...
f1=@(x) C1*x.^2;
f2=@(x) C2*f1(x);
f3=@(x) C3*f1(x).*f2(x);
This way, of course, the values of the constants are embedded in the function definitions and are insensitive to subsequent changes in those values; if need to redefine C then define the functions as functions of (x,C) and pass the constants.

3 Comments

I tried to write it like any other expression, however matlab wasn't understanding what I was trying to evaluate. Once I put my functions in parenthisis as you can see below, my expressions worked. I still don't understand why I need to put parenthisis around it, and if you have an explanation for that I would be glad to hear it. What is the difference between rho_h(h) and (rho_h(h))
rho=[.413,.467,.526,.590,.660,.736,.819,.909,1.007,1.112,1.225];
height=[10000:-1000:0];
p=polyfit(height,rho,2);
rho_h=@(h) p(1)*h^2+p(2)*h+p(3);
CL_H=@(h) 2*Weight/(rho_h(h))/V^2/S_w;
Drag_h=@(h) (.5*(rho_h(h))*V^2*S_w)*((f/S_w)+((CL_H(h))^2/pi/e/AR))*Cdi;
Nothing. There is no difference. Note that dpb's code does not use parentheses around the function calls. When I remove the parentheses from around the two rho_h calls in your code:
CL_H=@(h) 2*Weight/rho_h(h)/V^2/S_w;
Drag_h=@(h) (0.5*rho_h(h)*V^2*S_w)*((f/S_w)+((CL_H(h))^2/pi/e/AR))*Cdi;
it gives exactly the same answer (using the value 1 for all of the undefined variables):
>> Drag_h(1)
ans =
1.132
NB: the real difference in the functions as you've written them vis a vis the way I did is the "dot" operator on the exponent. If you try to pass a vector h yours will fail for that reason. Perhaps you've misdiagnosed the cause of an error, maybe? We've not seen the error you received so can only guess, of course...

Sign in to comment.

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Asked:

on 9 Dec 2015

Commented:

dpb
on 9 Dec 2015

Community Treasure Hunt

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

Start Hunting!