MATLAB: How to refer the value from a matrix when I do 2-dimensional integral operation

integral integral2 refer value matrix

Hi, I have a problem about integral operation. I'd like to do 2-dimensional integral calculation with reference matrix A. For example,
N=10;
A = ones(N,N);
fun = @(x,y) x+y+A(round(x),round(y));
ans = integral2(fun,1,N,1,N);
I'd like to refer a value from matrix A while doing integral operation. But this program doesn't work.
If you have some solution or comments, please let me know.
Regards, Haruka

Best Answer

When performing integration, integral2 function provides fun with x,y as matrices, not necessarily scalars. In other words, the integrand needs to work properly with the matrix inputs.
When x and y are M by N matrices in the above function, A(round(x), round(y)) becomes a M*N by M*N matrix. Thus
fun = @(x,y) x+y+A(round(x),round(y))
causes an error of matrix size mismatch.
I am guessing the following code would do the work as intended
A = magic(4)
xx = [1,2,3;2,3,4];
yy = [1,2,3;1,1,1];
Axy_vector = A(sub2ind(size(A),xx(:),yy(:)));
Axy_matrix = reshape(Axy_vector,size(xx))
Please check if the code refers to the value of A(1,1), A(2,2), A(3,3), A(2,1), A(3,1), A(4,1) and Axy_matrix is the same size as xx and yy.
I would suggest defining the following myfun.m,
function z = myfun(x,y,A)
xx = round(x);
yy = round(y);
Axy_vector = A(sub2ind(size(A),xx(:),yy(:)));
Axy_matrix = reshape(Axy_vector,size(xx));
z = x+y+Axy_matrix;
end
Then try
N=10;
A = ones(N,N);
IntA = integral2(@(x,y) myfun(x,y,A),1,N,1,N);
Hope it helps.