Trying to pass more than 2 vectors to a function i

2020-05-03 09:56发布

问题:

I want to compute e^(ax+b) over a=-1:1 and b=-1:1 for various values of X. I want the output in the form a list of 5 elements. Each element in the list is 3X3 Matrix.

I did achieve this using Outer and Vectorize.

 sigm = function(a=0,b=0,x){
 return(exp(x*a+b))
 }

 sigm1 = Vectorize(function(a=-1:1,b=-1:1,x){

 outer(a,b,sigm,x)
 },SIMPLIFY = FALSE)

Now, sigm1(x=1:3) gives the required output

 [[1]]
      [,1]      [,2]     [,3]
 [1,] 0.1353353 0.3678794 1.000000
 [2,] 0.3678794 1.0000000 2.718282
 [3,] 1.0000000 2.7182818 7.389056

[[2]]
       [,1]      [,2]       [,3]
[1,] 0.04978707 0.1353353  0.3678794
[2,] 0.36787944 1.0000000  2.7182818
[3,] 2.71828183 7.3890561 20.0855369

[[3]]
       [,1]        [,2]       [,3]
[1,] 0.01831564  0.04978707  0.1353353
[2,] 0.36787944  1.00000000  2.7182818
[3,] 7.38905610 20.08553692 54.5981500

The only draw back with this code snippet is I am using the default values of a=-1:1 and b=-1:1. When I try to pass the same during function calling, it goes haywire. E.g.

sigm1(-1:1,-1:1,1:3)

[[1]]
      [,1]
[1,] 0.1353353

[[2]]
 [,1]
[1,]    1

[[3]]
     [,1]
[1,] 54.59815

I am unable to figure out why passing the arguments is making this difference in output.

回答1:

In this case, you should only vectorize the variable x.

sigm1 = Vectorize(function(a=-1:1,b=-1:1,x){
                    outer(a,b,sigm,x)}, vectorize.args = "x" ,SIMPLIFY = FALSE)

Then running sigm1(-1:1,-1:1,1:3) will gives the result you want.



回答2:

We can just use lapply and don't need Vectorize at all:

lapply(x, function(x) outer(a, b, sigm, x = x))

giving:

[[1]]
          [,1]      [,2]     [,3]
[1,] 0.1353353 0.3678794 1.000000
[2,] 0.3678794 1.0000000 2.718282
[3,] 1.0000000 2.7182818 7.389056

[[2]]
           [,1]      [,2]       [,3]
[1,] 0.04978707 0.1353353  0.3678794
[2,] 0.36787944 1.0000000  2.7182818
[3,] 2.71828183 7.3890561 20.0855369

[[3]]
           [,1]        [,2]       [,3]
[1,] 0.01831564  0.04978707  0.1353353
[2,] 0.36787944  1.00000000  2.7182818
[3,] 7.38905610 20.08553692 54.5981500