DolphinDB: How to perform matrix-like multiplication on tables?

16 views Asked by At

I create two tables, tb1 and tb2, with the following script:

tb1=table(`sym1`sym2`sym3`sym4`sym5 as SYMBOL,NULL NULL 1 NULL NULL as block1,NULL 1 NULL NULL NULL as block2,1 NULL NULL 1 NULL as block3,NULL 1 NULL NULL 1 as block4)
tb2=table(`sym1`sym2`sym3`sym4`sym5 as SYMBOL,1+double(seq(1,5))/10 as col1,2+double(seq(1,5))/10 as col2,3+double(seq(1,5))/10 as col3)

I want to calculate the inner product between the non-null cell values of each “block” column in tb1 and the values in the corresponding cell in tb2, and return the result in the format of tb3, as shown in the figure below. How to achieve this in DolphinDB?

enter image description here

1

There are 1 answers

0
JaneYe On

You can convert tb1 and tb2 into matrices m1 and m2 and use the cross function to apply the wsum function to the permutation of all individual elements of m1 and m2. If the column names of the two matrices differ, use the align function to align the two matrices first. Refer to the following script and output:

tb1=table(`sym1`sym2`sym3`sym4`sym5 as SYMBOL,NULL NULL 1 NULL NULL as block1,NULL 1 NULL NULL NULL as block2,1 NULL NULL 1 NULL as block3,NULL 1 NULL NULL 1 as block4)
tb2=table(`sym1`sym3`sym4 as SYMBOL,1+double(seq(1,3))/10 as col1,2+double(seq(1,3))/10 as col2,3+double(seq(1,3))/10 as col3)

m1 = matrix(tb1[,1:]).rename!(tb1.SYMBOL, tb1.colNames()[1:])
m2 = matrix(tb2[,1:]).rename!(tb2.SYMBOL, tb2.colNames()[1:])
mm1, mm2 = align(m1, m2, 'fj', true)
re = cross(wsum, mm1, mm2)
col1 col2 col3
block1 1.2 2.2 3.2
block2
block3 2.4 4.4 6.4
block4