2
$\begingroup$

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.

$\endgroup$
4
  • $\begingroup$ How is conv2 defined in MATLAB? $\endgroup$
    – Michael E2
    Apr 11, 2019 at 1:43
  • 1
    $\begingroup$ @MichaelE2 here is the link: fr.mathworks.com/help/matlab/ref/conv2.html $\endgroup$
    – Ali Hashmi
    Apr 11, 2019 at 1:45
  • 2
    $\begingroup$ 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. $\endgroup$
    – eyorble
    Apr 11, 2019 at 1:49
  • $\begingroup$ @eyorble agreed. but ListConvolve should be able to handle this case $\endgroup$
    – Ali Hashmi
    Apr 11, 2019 at 1:53

1 Answer 1

8
$\begingroup$

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]

enter image description here

For comparision, here is the output of Octave:

enter image description here

$\endgroup$
2
  • $\begingroup$ thanks. upvoted. i will accept the answer in a couple of days ! $\endgroup$
    – Ali Hashmi
    Apr 11, 2019 at 18:08
  • $\begingroup$ @AliHashmi Feel free to wait for better answer(s) :) . $\endgroup$
    – xzczd
    Apr 12, 2019 at 2:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.