Lua计算kronecker 积、Khatri-Rao积、Hadamard积、普通矩阵乘积
function Kron(A,B,mark)
local C ={}
if mark==0
then
rowC=row_A*row_B
colC=col_A*col_B
else
rowC = row_A*row_B
colC = 1
end
for i=1,rowC do
C[i]={}
x2=i%row_B
if x2==0
then
x2=row_B
end
for j=1,colC do
y2=j%col_B
if y2==0
then
y2=col_B
end
C[i][j]=A[math.ceil(i/row_B)][math.ceil(j/col_B)]*B[x2][y2]
end
end
return C
end
print("please input the row and col of matrix A:")
row_A=tonumber(io.read())
col_A=tonumber(io.read())
print("please input matrix A:")
A={}
for i=1,row_A do
A[i]={}
for j=1,col_A do
A[i][j]=tonumber(io.read())
end
end
print("please input the row and col of matrix B:")
row_B=tonumber(io.read())
col_B=tonumber(io.read())
print("please input matrix B:")
B={}
for i=1,row_B do
B[i]={}
for j=1,col_B do
B[i][j]=tonumber(io.read())
end
end
print("matrix A:")
for i=1,row_A do
a = ""
for j=1,col_A do
a = a..A[i][j].." "
end
print(a)
end
print("matrix B:")
for i=1,row_B do
b=""
for j=1,col_B do
b=b..B[i][j].." "
end
print(b)
end
print("please make choice: 1--kronecker, 2--AB normal product,3--A*B Khatri-Rao,4--A@B Hadamard")
flag=tonumber(io.read())
if flag==1
then
C = Kron(A,B,0)
row_C=row_A*row_B
col_C=col_A*col_B
print("the kronecker of A B is matrix C:")
elseif flag == 2
then
C={}
row_C=row_A
col_C=col_B
for i=1,row_A do
C[i]={}
for j=1,col_B do
C[i][j]=0
for k=1,col_A do
C[i][j]=C[i][j]+A[i][k]*B[k][j]
end
end
end
print("the normal product of A B is matrix C:")
elseif flag == 4
then
C = {}
for i=1,row_A do
C[i]={}
for j=1,col_A do
C[i][j]=A[i][j]*B[i][j]
end
end
print("the Hadamard product of A B is matrix C:")
row_C=row_A
col_C = col_A
elseif flag==3
then
row_C=row_A*row_B
col_C=col_A
C={}
for i=1,row_C do
C[i]={}
end
AA={}
BB={}
for i=1,col_A do
for j=1,row_A do
AA[j]={}
AA[j][1]=A[j][i]
end
for k=1,row_B do
BB[k]={}
BB[k][1]=B[k][i]
end
DD=Kron(AA,BB,1)
for t=1,row_C do
C[t][i]=DD[t][1]
end
end
print("the Khatri-Rao product of A B is matrix C:")
end
for i=1,row_C do
c=""
for j=1,col_C do
c=c..C[i][j].." "
end
print(c)
end