MATLAB: Fastest way to implement the given lines of code.

speedtimevectorization

Let A, B, C be any random matrices of order mxn; m,n would be large enough. What is the fastest way to implement the following lines:
A = rand(m,n) ;
B = rand(m,n) ;
C = rand(m,n) ;
t1 = tic ;
for j = 2:n
for i = 2:m
H = 0.5*(A(i,j) + A(i+1,j)) ;
if (H > 0.0)
C(i,j) = C(i,j)-H*(B(i+1,j)-B(i,j)) ;
end
end
end
toc(t1)
cheers...
Sreenivas

Best Answer

I suspect you're looking for something like the following,
A = rand(m,n) ;
B = rand(m,n) ;
C = rand(m,n) ;
H=0.5*conv2(A,[1;1],'same'); %EDITED
deltaB=conv2(B,[1;-1],'same');
idx=H>0;
C(idx)=C(idx)-H(idx).*deltaB(idx);
Related Question