如何在Julia中乘以多维数组/矩阵 [英] How to multiply multi-dimensional arrays/matrices in Julia

查看:214
本文介绍了如何在Julia中乘以多维数组/矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将两个多维数组(例如,一维数组和3维数组)相乘:

Multiplying two multi-dimensional arrays, say, a 1-dimensional with a 3-dimensional array:

[1 2] * reshape(1:8,2,2,2)

给我错误消息:

LoadError: MethodError: `*` has no method matching *(::Array{Int64,2}, ::Array{Int64,3})
Closest candidates are:
  *(::Any, ::Any, !Matched::Any, !Matched::Any...)
  *{TA,TB}(::Union{DenseArray{TA,1},DenseArray{TA,2},SubArray{TA,1,A<:DenseArray{T,N},I<:Tuple{Vararg{Union{Colon,Int64,Range{Int64}}}},LD},SubArray{TA,2,A<:DenseArray{T,N},I<:Tuple{Vararg{Union{Colon,Int64,Range{Int64}}}},LD}}, !Matched::Base.LinAlg.AbstractTriangular{TB,S<:AbstractArray{T,2}})
  *{TA,TQ,N}(::Union{DenseArray{TA,N},SubArray{TA,N,A<:DenseArray{T,N},I<:Tuple{Vararg{Union{Colon,Int64,Range{Int64}}}},LD}}, !Matched::Union{Base.LinAlg.QRCompactWYQ{TQ,M<:AbstractArray{T,2}},Base.LinAlg.QRPackedQ{TQ,S<:AbstractArray{T,2}}})
  ...
while loading In[167], in expression starting on line 1

 in Ac_mul_B at operators.jl:157

使用多维矩阵代数的数学定义对矩阵/数组进行(1 x 2)*(2 x 2 x 2)乘法.

using the math definition of multi-dimensional matrix algebra for a (1 by 2) * (2 by 2 by 2) multiplication of matrices/arrays.

更一般的示例可以是A * B = C,表示sum_k A_ {i,j,k} B_ {k,l,m} = C_ {i,j,l,m},其中A是3 -index矩阵,或者张量(如果愿意),B是3索引矩阵,而生成的C是4索引矩阵/张量,但是,通常,可以有任意数量的维度,并且维度可以具有任何大小(在合理范围内).查看有关矩阵产品

A somewhat more general example can be A*B = C meaning sum_k A_{i,j,k} B_{k,l,m} = C_{i,j,l,m}, where A is a 3-index matrix, or tensor if you like, B is a 3-index one, and the resulting C is a four index matrix/tensor, but, in general, there can be any number of dimensions and a dimension can have any size (within reason). See more info on the definition of a matrix product or tensor contraction.

Julia中此乘法的正确语法是什么?

What is the right syntax of this multiplication in Julia?

推荐答案

您可以使用reshape将多维数组转换为矩阵, 将它们相乘,然后将结果转换回多维数组.

You can use reshape to convert the multi-dimensional arrays into matrices, multiply them, and convert the result back to a multi-dimensional array.

A = [1 2]
B = reshape(1:8,2,2,2)
reshape( reshape(A,2,1)' * reshape(B,2,4), 2, 2 )

(在此示例中,由于A已经是矩阵,因此实际上无需重塑形状.)

(In this example, since A is already a matrix, there is actually no need to reshape it.)

这篇关于如何在Julia中乘以多维数组/矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆