How do I call and multiply handles from an array in integral or quad function?

1 view (last 30 days)
Hello. For my homework I'm trying to approximate a function with Least squares method, but I face a problem with the function quad(integral). I would like to integrate multiplied elements from B (which are actually handle functions). I have an array of functions:
B= @(x) [1, sin(x), cos(x),sin(x).*cos(x)]; %base functions
and I would like to make a matrix A of integrated multiplied functions. So I have to get 4x4 matrix with integrals of multiplied functions such as : in the first column I would like to have integrals of 1*1, 1*sin(x), 1*cos(x), 1*sin(x)*cos(x); in the second column integrals of sin(x)*1, sin(x)*sin(x), sin(x)*cos(x), sin(x)*cos(x)*sin(x) etc.
My problem is that functions QUAD or INTEGRAL are returning me errors. I have tried everything I found around the internet but no success.
Here is my code:
function ap = MNK(n)
B= @(x) [1, sin(x), cos(x),sin(x).*cos(x)];
A=zeros(n,n);
%f = @x exp(x(x+1))
for i=1:n
for j=1:n
A(i,j) = integral(@(x)B(i)*B(j),-1,1); %problem
end
%b(i)=quad(@x B(i).*f(x),-1,1,1e-12); %second part, same problem (just the second function is not base function but our function f)
end
end
So my question is: How do I call and multiply handles from array B in my integral(or quad) function. Please, I could use any help, because I'm stuck for 2 days now.

Accepted Answer

Andrew Newell
Andrew Newell on 17 Apr 2017
You can replace B by a cell array of functions, and then call the functions when it's time to integrate:
Bfuns = {@(x) ones(size(x)), @sin, @cos, @(x)sin(x).*cos(x)};
%f = @x exp(x(x+1))
A=zeros(n,n);
for i=1:n
for j=1:n
A(i,j) = integral(@(x) Bfuns{i}(x).*Bfuns{j}(x),-1,1); %problem
end
%b(i)=quad(@x B(i).*f(x),-1,1,1e-12); %second part, same problem (just the second function is not base function but our function f)
end
Note that I had to use ones(size(x)) to make sure it outputs a vector of the appropriate size. I didn't include the function statement because I don't know how ap is related to A and b.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!