alternative for tensorprod that is coder compatible

6 ビュー (過去 30 日間)
Matthias Kreuzer
Matthias Kreuzer 2022 年 12 月 14 日
コメント済み: Matthias Kreuzer 2022 年 12 月 23 日
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 Center および File ExchangeDescriptive Statistics についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by