How do I multiply two inline functions together to produce a third within MATLAB?

12 views (last 30 days)
I have two inline functions that I want to multiply together to produce a third. For example, if I have "f1" and "f2" I would like to create "f3" such that
f3 = f1*f2

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 13 Jul 2009
This can be accomplished using a string concatenation technique. Given two functions "f1" and "f2", you can make a function "f3" that is the product of the first two using the following code:
f3 = inline(['(' char(f1) ')*(' char(f2) ')'])
"f3" will now be an inline function that is the product of "f1" and "f2". "f1" and "f2" can then be cleared from the workspace if so desired.
Another method is to create the following function:
f3 = inline('a(x)*b(x)','x','a','b')
We can now evaluate "f3" at any value "x" with the following:
f3(x,f1,f2)
This method, although visually easier to comprehend, requires that both "f1" and "f2" remain in the workspace you are using. As of MATLAB 7.0 (R14) there is a new object type known as the anonymous function that is better suited than the INLINE for this type of application. The same result can now be achieved using anonymous functions with the following code:
f3 = @(x)f1(x)*f2(x)
"f3" is now mathematically identical to what we created with the first two procedures using INLINE. The benefit in this case is that functions "f1" and "f2" now reside in the workspace of "f3", so they can be cleared from the workspace they were defined in with no loss of information to "f3". This is one of the many improvements the anonymous function offers over the INLINE. Anonymous functions are also much less computationally intensive than INLINEs resulting in a faster running time for programs that implement them.

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!