Interesting facts about "integral2"

2 views (last 30 days)
Marco D'Alessandro
Marco D'Alessandro on 23 May 2019
Answered: Karun Mathiazhagan on 30 May 2019
Hi guys,
I've noticed some weird facts about integral2. These are probably due to my limitations in understanding how it works. Look at the following Code:
function Output = prova(p,Y)
x = p(1);
y = p(2);
w = p(3);
z = p(4);
F1 = @(Data,eta_1,eta_2,x,y,w,z) F2(eta_1,eta_2,Data) .* normpdf(eta_1,x,y) .* normpdf(eta_2,w,z);
Output = integral2(@(eta_1,eta_2)F1(Y,eta_1,eta_2,0,1,10,2),-5,5,-5,5);
end
function O = F2(pp1,pp2,D)
O = pp1 + pp2 + sum(D);
end
where Y is a vector.
If I change the code in this way I obtain some errors, although the output of F2 is exactly the same:
function Output = prova(p,Y)
x = p(1);
y = p(2);
w = p(3);
z = p(4);
F1 = @(Data,eta_1,eta_2,x,y,w,z) F2(eta_1,eta_2,Data) .* normpdf(eta_1,x,y) .* normpdf(eta_2,w,z);
Output = integral2(@(eta_1,eta_2)F1(Y,eta_1,eta_2,0,1,10,2),-5,5,-5,5);
end
function O = F2(pp1,pp2,D)
o = sum([pp1 pp2]);
O = o + sum(D);
end
Now, if I write the function F2 as before, but I change just the way F2 takes the input, I obtain a warning:
function Output = prova(p,Y)
x = p(1);
y = p(2);
w = p(3);
z = p(4);
F1 = @(Data,eta_1,eta_2,x,y,w,z) F2([eta_1,eta_2],Data) .* normpdf(eta_1,x,y) .* normpdf(eta_2,w,z);
Output = integral2(@(eta_1,eta_2)F1(Y,eta_1,eta_2,0,1,10,2),-5,5,-5,5);
end
function O = F2(pp,D)
O = pp(1) + pp(2) + sum(D);
end
This problems makes practically impossible to solve problems in which, for instance, we have to integrate out a variable X which is inside a Likelihood Function (whose calculation could require some internal Loop, or Sum, or Prod of involving our variable X). What is the solution?

Answers (1)

Karun Mathiazhagan
Karun Mathiazhagan on 30 May 2019
Hello Marco,
I feel that it would be a good idea to make sure that all three of the versions of the function "F2" are guaranteed to return the same results even for vector inputs. The function "integral2" calls the integrand function for vector (both rows and columns) inputs as well in the back-end for the evaluation of the double integral. When it does, it would be important for it to use correctly vectorized "F1" and "F2" functions so as to make sure that the results obtained are accurate.
For example, for row vector inputs "pp1 + pp2" would be equivalent to "sum([pp1 pp2])". But for column vector inputs, "pp1 + pp2" would be equivalent to "sum([pp1 pp2], 2)" instead.
I hope this helps.
Best,
Karun

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!