Learning R - What is this Function Doing? -


i learning r , reading book guide programming algorithms in r.

the book give example function:

# matrix-vector multiplication matvecmult = function(a,x){     m = nrow(a)     n = ncol(a)      y = matrix(0,nrow=m)     (i in 1:m){         sumvalue = 0                 (j in 1:n){             sumvalue = sumvalue + a[i,j]*x[j]         }         y[i] = sumvalue     }     return(y) } 

how call function in r console? , passing function a, x?

the function takes argument a, should matrix, , x, should numeric vector of same length values per row in a.

if

a <- matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3)       [,1] [,2] [,3] [1,]    1    3    5 [2,]    2    4    6 

then have 3 values (number of columns, ncol) per row, x needs

x <- c(4,5,6) 

the function iterates rows, , in each row, each value multiplied value x, value in first column multiplied first value in x, value in as second column multiplied second value in x , on. repeated each row, , sum each row returned function.

matvecmult(a, x)       [,1] [1,]   49 # 1*4 + 3*5 + 5*6 [2,]   64 # 2*4 + 4*5 + 6*6 

to run function, first have compile (source) , consecutively run these 3 code lines:

a <- matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3) x <- c(4,5,6) matvecmult(a, x) 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -