MATLAB: Double integral of a dot product error

errorfunctionintegalintegrationnumerical integration

I'm tring to solve a double integral in matlab where two dot products are evaluated, but an error arieses.
The code is:
light_dir = [-0.6626;0;-0.7490];
camera_dir = [-1;0;0];
R = sqrt(2/(4*pi));
x_c =@(theta,phi) R.*sin(theta).*cos(phi);
y_c =@(theta,phi) R.*sin(theta).*sin(phi);
z_c =@(theta) R.*cos(theta);
normal =@(theta,phi) [x_c(theta,phi); y_c(theta,phi); z_c(theta)];
fun = @(theta,phi) (dot(light_dir,normal(theta,phi))).*(dot(camera_dir,normal(theta,phi))<0).*R^2.*sin(theta);
intensity = integral2(fun,0,pi,0,2*pi);
The error is:
Error using dot (line 39)
A and B must be same size.
Error in Image_processing (line 246)
fun = @(theta,phi)
(dot(light_dir,normal(theta,phi))).*(dot(camera_dir,normal(theta,phi))<0).*R^2.*sin(theta);
Error in integral2Calc>integral2t/tensor (line 228)
Z = FUN(X,Y); NFE = NFE + 1;
Error in integral2Calc>integral2t (line 55)
[Qsub,esub] = tensor(thetaL,thetaR,phiB,phiT);
Error in integral2Calc (line 9)
[q,errbnd] = integral2t(fun,xmin,xmax,ymin,ymax,optionstruct);
Error in integral2 (line 106)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);
Error in Image_processing (line 248)
intensity = integral2(fun,0,pi,0,2*pi);
Do you have any suggestion to let it work?

Best Answer

  • integral2() assumes that the function handle is able to accept matrix inputs. However, the fun() function in your code does not work correctly with matrix inputs. The following codes shows a quick fix using arrayfun
    light_dir = [-0.6626;0;-0.7490];
    camera_dir = [-1;0;0];
    R = sqrt(2/(4*pi));
    x_c =@(theta,phi) R.*sin(theta).*cos(phi);
    y_c =@(theta,phi) R.*sin(theta).*sin(phi);
    z_c =@(theta) R.*cos(theta);
    normal =@(theta,phi) [x_c(theta,phi); y_c(theta,phi); z_c(theta)];
    fun = @(theta,phi) (dot(light_dir,normal(theta,phi))).*(dot(camera_dir,normal(theta,phi))<0).*R^2.*sin(theta);
    intensity = integral2(@(THETA, PHI) arrayfun(@(theta,phi) fun(theta, phi), THETA, PHI) ,0,pi,0,2*pi);