How do I multiply two inline functions together to produce a third within MATLAB?
7 次查看(过去 30 天)
显示 更早的评论
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
采纳的回答
MathWorks Support Team
2009-7-13
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.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!