alternative for tensorprod that is coder compatible

5 次查看(过去 30 天)
Hi,
I have implemented a custom 2D convolution layer. Since nested loops were too slow I rearranged my input U and my filter weights V to be of dimensions (filter_width *filter_height) x input channels x (output_width *output_height) and (filter_width *filter_height) x input channels x number of filters and then used the tensorprod function and reshaped the output to output_height x output_width x number of filters.
To my actual problem: I have two 3-D tensors for which I want to compute a tensor product, which contracts the first two dimensions of each tensor with each other.
U: a x b x c
V: a x b x d
W = tensorprod(U,V,[ 1 2])
W will then be of dimensions c x d.
I cannot use the Matlab tensorprod function because it is not Matlab coder compatible. Is there another fast solution to compute W, which is also compatible with Matlab coder?
  1 个评论
Matthias Kreuzer
Matthias Kreuzer 2022-12-23
I solved it myself
function result = mytensorprod(A,B,dims)
% performs the tensor product for matrices A and B
% A and B are contracted along the dimensions specified in dims
% First A and B are permuted to perform the inner product
% Same functionality as the matlab function tensorprod
sizeA = size(A); sizeB = size(B);
dimAouter = 1:length(sizeA); dimAouter(dims)=[];
dimBouter = 1:length(sizeB); dimBouter(dims)=[];
Ap = permute(A,[dimAouter,dims]);
Apr = reshape(Ap,[prod(sizeA(dimAouter)),prod(sizeA(dims))]);
Bp = permute(B,[dims,dimBouter]);
Bpr = reshape(Bp,[prod(sizeB(dims)),prod(sizeB(dimBouter))]);
result = Apr*Bpr;
result = reshape(result,[sizeA(dimAouter),sizeB(dimBouter)]);
end

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Linear Algebra 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by