MATLAB: Function handle integration with several variable, matrix dimension error

dimensiondirachandlesMATLAB

Hi! I am using function handles to integrate with several variables (note: I made the same program using symbolic integration, but it takes a really long time). However, I keep getting an error in matrix dimensions in the last line of my when I plug in R(1) and I really can't figure out what is wrong. Any tips would be greatly appreciated!
FUN_1 = @(y_1,y_2,x_1,x_2)sum(heaviside(y_1-1)).*dirac(1,y_2-1).*(-1/2*log((x_1-y_1).^2+(x_2-y_2).^2))+sum(dirac(y_1-1).*dirac(y_2-1));
Q_1 = @(x_1,x_2)integral2(@(y_1,y_2)FUN_1(y_1,y_2,x_1,x_2),1,2,1,2);
FUN_2 = @(y_1,y_2,x_1,x_2)sum(heaviside(y_1-1).*dirac(1,y_2-1))+sum(dirac(y_1-1).*dirac(y_2-1))*(-1/2*log((x_1-y_1).^2+(x_2-y_2).^2));
Q_2 = @(x_1,x_2)integral2(@(y_1,y_2)FUN_1(y_1,y_2,x_1,x_2),1,2,1,2);
S = @(x_1,x_2)Q_1(x_1,x_2)+Q_2(x_1,x_2);
R = @(x_2)integral(@(x_1)S(x_1,x_2),1,2);
b = R(1);
disp(b)

Best Answer

integral() calls the function passing in a vector of values. So your S will be called with a vector x_1, so your Q_1 will be called with a vector x_1. Your Q_1 calls integral2, which is going to call FUN_1 with array y_1 and y_2 (the same size) and the vector x_1 (of different size). Your FUN_1 expects x_1 and y_1 to be compatible size for subtraction, but the two are not compatible.
You could use the 'ArrayValued' option of integral so that it only passes in a scalar for x_1, at a cost to efficiency. You should look more carefully at which operations can be vectorized. Sometimes it helps to use arrayfun() along the way.
Related Question