# Analog of MATLAB's conv2 in Mathematica?

I have a matlab code

filter = 1;
F = conv2(double([1 2 1]),double([1 2 1]'))/16;
for i=1:some_integer
filter = conv2(double(filter),double(F));
end


In the code F = conv2(double([1 2 1]),double([1 2 1]'))/16; equals a 3 x 3 matrix {{0.0625, 0.125, 0.0625}, {0.125, 0.25, 0.125}, {0.0625, 0.125, 0.0625}}

filter changes the value in the first iteration from 1 to F and then in successive iteration the result (convolution matrix) gets larger and larger.

I am having trouble doing this convolution in Mathematica despite having looked at the documentation. Any idea how one might do such a convolution?

My attempt below to compute F before the loop looks incorrect somehow.

F = Flatten[(ListConvolve[{{0, 0, 0}, {1, 2, 1}, {0, 0, 0}},
{{1, 2, 1}, {1, 2, 1}, {1, 2, 1}}, {-1, 1}, g, Plus, List]/16.0 ), 2]


because the same formulation for ListConvolve as shown above does not work for filter inside the loop.

• How is conv2 defined in MATLAB? – Michael E2 Apr 11 '19 at 1:43
• @MichaelE2 here is the link: fr.mathworks.com/help/matlab/ref/conv2.html – Ali Hashmi Apr 11 '19 at 1:45
• The calculation of F (testing using octave) appears to be identical to Transpose[Outer[Times, {1,2,1}, {1,2,1}]] (the Transpose is there for generality, but the result is symmetric in this case). Assuming filter is not a higher-order tensor by the end, however, Outer is not the same thing as conv2. – eyorble Apr 11 '19 at 1:49
• @eyorble agreed. but ListConvolve should be able to handle this case – Ali Hashmi Apr 11 '19 at 1:53

Not sure if I've guessed definition of conv2 accurately, but the following does reproduce the output of MATLAB. (Tested in Octave. )

conv2[A_?NumericQ, B_] := conv2[{{A}}, B]
conv2[A_?VectorQ, B_] := conv2[{A}, B]
conv2[A_, B_] := ListConvolve[A, B, {1, -1}, 0]

filter = 1;
F = conv2[{1, 2, 1}, List /@ {1, 2, 1}]/16.;
Nest[conv2[#, F] &, filter, 3] For comparision, here is the output of Octave: • thanks. upvoted. i will accept the answer in a couple of days ! – Ali Hashmi Apr 11 '19 at 18:08
• @AliHashmi Feel free to wait for better answer(s) :) . – xzczd Apr 12 '19 at 2:28