绘制矩阵乘法

时间:2018-12-07 10:55:22

标签: r matrix plot

我试图绘制一个矩阵乘积作为时间的函数,并遇到一个问题,即无法将原始状态包括在图中(其中n = c(100,1000,50))。

我尝试在其他SO帖子中搜索解决方案,但只能找到next函数,我认为这不好,因为如果我将其写入if (time ==1){}部分,则会跳过原始状态不变。最终,我想到了这一点,但它也不起作用:

n = c(100,1000,50) #original state
G = matrix(c(0.6,0.4,0,0.005,0.9,0.1,0,0,0.5),3,3) 

population = function(time = 100){
  x = seq(0,100,1)
  plot(x = seq(0,100,1),y = seq(0,1000,10), col="white", xlab = "time", ylab = "sample")
  if(time == 1){
    points(x[1],n[1], col = "red") 
    points(x[1],n[2], col = "blue")
    points(x[1],n[3], col = "black")
  }
  for(i in 1:(time-1)){
    n = G%*%n
    print(n)
    points(x[i],n[1], col = "red") 
    points(x[i],n[2], col = "blue")
    points(x[i],n[3], col = "black")

  }
  return(n)

} 

population(100)

任何提示将不胜感激。

1 个答案:

答案 0 :(得分:0)

我宁愿使用函数matplot,因为真正控制它实际产生的内容更容易。而且,代码变得更加清晰。

N <- matrix(NA, 3, 100)
N[, 1] <- c(100, 1000, 50)
G <- matrix(c(0.6, 0.4, 0, 0.005, 
              0.9, 0.1, 0, 0, 0.5), 3, 3) 
for (i in 2:ncol(N)) {
  N[,i] <- G %*% N[, i-1]
}
matplot(x=0:99, t(N), type = "p", pch=1,
        xlab = "time", ylab = "N")

The result with matplot