Clear Filters
Clear Filters

alternative for tensorprod that is coder compatible

2 views (last 30 days)
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 Comment
Matthias Kreuzer
Matthias Kreuzer on 23 Dec 2022
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

Sign in to comment.

Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!