简体   繁体   中英

In R, How to plot a graph for this particular function?

fun = function(lambda) {-y %*% log(a %*% lambda) + lambda %*% apply(a,2,sum)}

in Maths notation.

Here lambda is a 2*1 matrix, a is a 5*2 matrix, y is a 1*5 matrix.

So i would like to plot fun(lambda) from (1:10, 1:10), Use persp() (or other command).

You're almost there. You just need to create a grid of values (1:10, 1:10) over which to evaluate your function. I've used dummy data to illustrate.

set.seed(123)
lambda<-as.matrix(runif(2),nrow=2)
a<-matrix(runif(10),ncol=2)
y<-runif(5)

fun = function(lambda) {-y %*% log(a %*% lambda) + lambda %*% apply(a,2,sum)}

#Create grid 
lambda.grid<-expand.grid(1:10,1:10)
names(lambda.grid)<-c("lambda_1","lambda_2")

z<-apply(lambda.grid,1,fun) #Evaluate function for each row

#Change z into matrix form for persp plots

z.mat<-matrix(z,ncol=10,byrow=FALSE)

persp(x=1:10,y=1:10,z.mat,xlab="lambda_1",ylab="lambda_2",zlab="f(lambda_1,lambda_2)")

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM