alternative for tensorprod that is coder compatible

6 vues (au cours des 30 derniers jours)
Matthias Kreuzer
Matthias Kreuzer le 14 Déc 2022
Commenté : Matthias Kreuzer le 23 Déc 2022
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 commentaire
Matthias Kreuzer
Matthias Kreuzer le 23 Déc 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

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Descriptive Statistics dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by