# 2D Matrix Convolution Question

This is probably very silly question. However, I could not find an answer for it.

given that I have Matrix A (with the size of NxN), and Kernel K (with the size of MxM) how I can get the output B, where: B = A*K? where * is the 2d-convolution sign

P.S. I did looked at torch.nn.functional.conv2d, but im not sure how we can define the kernel in that. I am not even sure if it is doing what I need…

I’m not sure if `conv2d` is what you’re looking for, but here’s how to adapt it to take your inputs.

Try this:

``````import torch
import torch.nn.functional as F
N = 4
M = 3
A = Variable(torch.randn(1, 1, N, N))
M = Variable(torch.ones(1, 1, M, M))
output = F.conv2d(A, M)
``````

You can set `A` to be any `N x N` matrix with `A[0,0,:] = A2`, where `A2` is `N x N`. Same with `M[0, 0, :] = M2` where `M2` is `M by M`.

1 Like

Yeah, Can you please tell me how would you do 2d convolution in pytorch if you dont want to use conv2d? or if you wanna use another way other than conv2…
I mean is there any other way to do it here in pytorch?

Thanks

with the functional.conv2d, the kernel is the `weight` argument

sorry for retrieving this question.
lets say i wanna do convolution with a specific filter on tensors.
e.g. my kernel is:
`H = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]])`, so it is `3x3` originally, but i can expand it in a size that is needed.
If my tensor T, has size of `BxCxDxD`, What should be the size and shape of my kernel so i can do `conv2d(T,H)` and get the output of `BxCxDxD`

what if i have RGB image (3xNxN) and 2D kernel (MxM)?