开发者

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

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

in Ma开发者_运维技巧ths 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜