我是R的初学者因此我的问题可能听起来很愚蠢。我有一个三维矩阵,它取决于两个参数(a和b),我需要了解它的特征值如何随着这些参数的不同值而变化。基本上我想使用persp绘制三个特征值(lambda1,lambda2,lambda3),以便了解它们何时为正,何时为负。
矩阵是:
a b a-b
a+b b a
a a b
其中-1&lt; a&lt; 1和-1&lt; 1 b <1。我的想法是做这样的事情:
a <- seq(-1,1,0.01)
b <- seq(-1,1,0.01)
lambda1 <- function(a,b){eigen(matrix(c(a,b,a-b,a+b,b,a,a,a,b),3,3,byrow=T))$values[[1]]}
C <- outer(a,b,lambda1)
nrC <- nrow(C)
ncC <- ncol(C)
Cfacet <- C[-1, -1] + C[-1, -ncC] + C[-nrC, -1] + C[-nrC, -ncC]
persp(a,b, C,col=ifelse(Cfacet>0,"red","white"))
然后以相同的方式进行以获得lambda2和lambda3的透视图。但是代码不起作用,并且R返回以下错误消息:
dims [product 40401] do not match the length of object [1]
我想我明白问题出在哪里(虽然不确定),但我无法弄清楚如何获得我想要的东西。有任何帮助或建议吗?
答案 0 :(得分:1)
这就是你所追求的:
require(akima) # akima package for easy surface interpolation
a <- seq(-1,1,0.01)
b <- seq(-1,1,0.01)
lambda1 <- function(a,b){eigen(matrix(c(a,b,a-b,a+b,b,a,a,a,b),3,3,byrow=T))$values[[1]]}
# make it a data frame for all permutations to fix the issue that
# your current code runs for a, b vectors so you get the same result 200x
mytab<-data.frame(expand.grid(a=a,b=b))
# use adply and transform to generate the 1st eigenvalues for each
# takes a while for 200 x 200! you could reduce a & b
mytab<-mytab<-adply(mytab, 1, transform, c = lambda1(a, b))
# use interp from akima to create 40x40 matrix - you can change this
surface<-interp(mytab$a,mytab$b,mytab$c)
# plot the surface
persp(surface$x,surface$y,surface$z,col=ifelse(surface$z>=0,"red","white"))
# you can also create a spinning plot like this:
require(rgl)
plot3d(1,1,3, # just an easy way to set the plot area
xlab="a",
ylab="b",
zlab="lambda1")
surface3d(surface$x,surface$y,surface$z,
col=ifelse(surface$z>=0,"red","white"), size=1)
编辑 - 根据没有AKIMA和PLYR依赖性的要求
a <- seq(-1,1,0.05)
b <- seq(-1,1,0.05)
lambda1 <- function(a,b){eigen(matrix(c(a,b,a-b,a+b,b,a,a,a,b),3,3,byrow=T))$values[[1]]}
mytab<-data.frame(expand.grid(a=a,b=b))
mytab$c<-apply(mytab, 1, function(x)lambda1(x["a"],x["b"]))
surface<-NULL
surface$x<-unique(mytab$a)
surface$y<-unique(mytab$b)
surface$z<-matrix(mytab$c,nrow=length(surface$x),byrow=TRUE)
persp(surface$x,surface$y,surface$z,col=ifelse(surface$z>=0,"red","white"))
答案 1 :(得分:0)
看起来outer()
将lambda1
解释为函数参数。我的建议是尝试像
C <- lambda1(outer(a,b))
我发现即使我尝试
,我也会遇到同样的错误 C <- outer(a,b, FUN = lambda1)