How to compute the dot product of two column (think full column as a vector)?

邮差的信 提交于 2021-02-08 19:39:26

问题


gave this table:

| a | b |  c | 
|---+---+----+
| 3 | 4 |    |
| 1 | 2 |    |
| 1 | 3 |    |
| 2 | 2 |    |

I want to get the dot product of two column a and b ,the result should be equel to (3*4)+(1*2)+(1*3)+(2*2) which is 21.

I don't want use the clumsy formula (B1*B2+C1*C2+D1*D2+E1*E2) because actually I have a large table waiting to calculate.

I know emacs's Calc tool has a "vprod" function which can do those sort of things ,but I dont' know how to turn the full column to a vector.

Can anybody tell me how to achieve this task,appreciate it!


回答1:


In emacs-calc, the simple product of 2 vectors calculates the dot product.

This works (I put the result in @6$3; also the parenthesis can be omitted):

| a | b | c  |
|---+---+----|
| 3 | 4 |    |
| 1 | 2 |    |
| 1 | 3 |    |
| 2 | 2 |    |
|---+---+----|
|   |   | 21 |
#+TBLFM: @6$3=(@I$1..@II$1)*(@I$2..@II$2)

@I and @II span from the 1st hline to the second.




回答2:


This can be solved using babel and R in org-mode:

#+name: mytable
| a | b |  c | 
|---+---+----+
| 3 | 4 |    |
| 1 | 2 |    |
| 1 | 3 |    |
| 3 | 2 |    |


#+begin_src R :var mytable=mytable
sum(mytable$a * mytable$b)
#+end_src

#+RESULTS:
: 23


来源:https://stackoverflow.com/questions/22837229/how-to-compute-the-dot-product-of-two-column-think-full-column-as-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!