You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建循环生成100个不同种子的随机方程时间序列并存储为矩阵

Generate 100 Stochastic Time Series with Unique Seeds (R)

Let's break this down into simple, actionable steps to get your 100 time series stored neatly in a matrix.

First, Set Up Your Fixed Parameters

Start by defining all constant values outside the loop—this avoids redundant computations and keeps your code clean:

N <- 100
T <- 1
x <- 10
theta <- c(0, 5, 3.5)
Dt <- 1/N
num_seeds <- 100  # Number of unique time series we want

Create a Matrix to Store Results

Each time series Y has N+1 data points (since you start at Y[1] and iterate up to Y[N+1]). We'll make a matrix with N+1 rows (one per observation) and num_seeds columns (one per seed):

Y_matrix <- matrix(nrow = N + 1, ncol = num_seeds)

Loop Through Each Seed to Generate Time Series

Now, we'll loop over each unique seed, generate the time series, and store it in the corresponding column of our matrix:

for (seed_idx in 1:num_seeds) {
  # Set a unique seed for this iteration
  set.seed(seed_idx)
  
  # Initialize your time series vector
  Y <- numeric(N + 1)
  Y[1] <- x
  
  # Generate random noise
  Z <- rnorm(N)
  
  # Run the stochastic loop to build Y
  for (i in 1:N) {
    Y[i + 1] <- Y[i] + (theta[1] - theta[2] * Y[i]) * Dt + theta[3] * sqrt(Dt) * Z[i]
  }
  
  # Convert Y to numeric (strip ts attributes) and store in the matrix
  Y_matrix[, seed_idx] <- as.numeric(Y)
}

Optional: Add Time Series Attributes to the Matrix

If you want the entire matrix to retain time series metadata (like start time and interval), you can convert it to a ts object:

Y_matrix_ts <- ts(Y_matrix, start = 0, deltat = Dt)

Quick Checks to Verify

  • Use dim(Y_matrix) to confirm the size: it should return 101 100 (101 rows for N+1 observations, 100 columns for 100 seeds).
  • To inspect a single time series, you can pull a column like Y_matrix[, 1] or Y_matrix_ts[, 1].

内容的提问来源于stack exchange,提问作者Salomon Santillan Salas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:27:59