BigbearZzz
BigbearZzz

Reputation: 103

Can a MATLAB function take mathematical functions as inputs?

I am totally new to this site and MATLAB, so please excuse me if my question is naive or a duplicate of some already existing question.

Well, I am a mathematics student, using MATLAB to aid in my project. There is a thing call "L^2 inner product" in which you need 2 mathematical functions, says f(x) and g(x), as inputs. It should work like

inner(f,g)=integrat f(x)*g(x) from 0 to 1.

The problem is I don't know how to write that in MATLAB.

To summarize, I want to make a MATLAB function whose inputs are two mathematical functions, the output is a real number. I know how to make an inline object but I don't know how to proceed further. Any help would be highly appreciated.

PS. I don't know if my tags are appropriate or on topic or not, please bear with me.

Upvotes: 0

Views: 64

Answers (1)

Matthew Gunn
Matthew Gunn

Reputation: 4529

I will build on what @transversality condition wrote in greater detail (eg. there should be a .*)

Illustrative example with anonymous functions

h = @sin % This assigns h the function handle of the sin function
         % If you know c, c++, this is basically a function pointer

inner = @(f,g)integral(@(x)f(x).*g(x),0,1) % This assigns  the variable inner
                                           % the function hanlde of a function which 
                                           % takes in two function handles f and g
                                           % and calculates the integral from 0 to 1
                         % Because of how Matlab works, you want .* here;
                         % you need f and g to be fine with vector inputs.

inner(h, @cos)           %this will calculate $\int_0^1 sin(x)cos(x)dx$

This yields 0.354

Writing inner as a regular function

In the previous example, inner was a variable, and the value of the variable was a function handle to a function which calculates the inner product. You could also just write a function that calculates the inner product. Create a file myinner.m with the following code:

function y = myinner(f, g)
y = integral(@(x)f(x).*g(x),0,1);

You could then call myinner the same way:

myinner(@sin, @cos)

result: 0.354

Note also that the integral function calculates the integral numerically and in strange situations, it's possible to have numerical problems.

Upvotes: 1

Related Questions