美文网首页
R的outer函数与外积

R的outer函数与外积

作者: 城管大队哈队长 | 来源:发表于2020-01-11 10:36 被阅读0次

    今天突然看到一个叫outer的R函数,发现特别好玩。

    > outer(1:4, 1:3, FUN = "paste", sep = ",")
         [,1]  [,2]  [,3] 
    [1,] "1,1" "1,2" "1,3"
    [2,] "2,1" "2,2" "2,3"
    [3,] "3,1" "3,2" "3,3"
    [4,] "4,1" "4,2" "4,3"
    

    然后在网上查了下其用法,其默认的FUN是乘法,所以其实本身是为了求外积的。外积的公式是这样的

    \begin{bmatrix}b_1 \\ b_2 \\ b_3 \\ b_4\end{bmatrix} \otimes \begin{bmatrix}a_1 & a_2 & a_3\end{bmatrix} = \begin{bmatrix}a_1b_1 & a_2b_1 & a_3b_1 \\ a_1b_2 & a_2b_2 & a_3b_2 \\ a_1b_3 & a_2b_3 & a_3b_3 \\ a_1b_4 & a_2b_4 & a_3b_4\end{bmatrix}
    那么我们对应过来如果我们要求1:4和1:3的外积,就是
    \begin{bmatrix}1 \\ 2 \\ 3 \\ 4\end{bmatrix} \otimes \begin{bmatrix}1 & 2 & 3 \end{bmatrix} = \begin{bmatrix}1 & 2 & 3 \\ 2 & 4 & 6 \\ 3 & 6 & 9 \\ 4 & 8 & 12\end{bmatrix}
    R出来结果跟我们手动算是一样的

    > outer(1:4,1:3)
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    2    4    6
    [3,]    3    6    9
    [4,]    4    8   12
    

    我们也可以像下面这么做,让我们更好地理解外积。

    > outer(1:4, 1:3, FUN = "paste", sep = "*")
         [,1]  [,2]  [,3] 
    [1,] "1*1" "1*2" "1*3"
    [2,] "2*1" "2*2" "2*3"
    [3,] "3*1" "3*2" "3*3"
    [4,] "4*1" "4*2" "4*3"
    

    当然,这个outer函数还可以画出久久乘法表

    > outer(1:9, 1:9, FUN = "paste", sep = "*")
          [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] 
     [1,] "1*1" "1*2" "1*3" "1*4" "1*5" "1*6" "1*7" "1*8" "1*9"
     [2,] "2*1" "2*2" "2*3" "2*4" "2*5" "2*6" "2*7" "2*8" "2*9"
     [3,] "3*1" "3*2" "3*3" "3*4" "3*5" "3*6" "3*7" "3*8" "3*9"
     [4,] "4*1" "4*2" "4*3" "4*4" "4*5" "4*6" "4*7" "4*8" "4*9"
     [5,] "5*1" "5*2" "5*3" "5*4" "5*5" "5*6" "5*7" "5*8" "5*9"
     [6,] "6*1" "6*2" "6*3" "6*4" "6*5" "6*6" "6*7" "6*8" "6*9"
     [7,] "7*1" "7*2" "7*3" "7*4" "7*5" "7*6" "7*7" "7*8" "7*9"
     [8,] "8*1" "8*2" "8*3" "8*4" "8*5" "8*6" "8*7" "8*8" "8*9"
     [9,] "9*1" "9*2" "9*3" "9*4" "9*5" "9*6" "9*7" "9*8" "9*9"
    

    还可以把月份和年份连起来一起打印:

    > outer(month.abb, 2019:2020, FUN = "paste")
          [,1]       [,2]      
     [1,] "Jan 2019" "Jan 2020"
     [2,] "Feb 2019" "Feb 2020"
     [3,] "Mar 2019" "Mar 2020"
     [4,] "Apr 2019" "Apr 2020"
     [5,] "May 2019" "May 2020"
     [6,] "Jun 2019" "Jun 2020"
     [7,] "Jul 2019" "Jul 2020"
     [8,] "Aug 2019" "Aug 2020"
     [9,] "Sep 2019" "Sep 2020"
    [10,] "Oct 2019" "Oct 2020"
    [11,] "Nov 2019" "Nov 2020"
    [12,] "Dec 2019" "Dec 2020"
    

    参考资料

    相关文章

      网友评论

          本文标题:R的outer函数与外积

          本文链接:https://www.haomeiwen.com/subject/kxpvactx.html