# What happens when we give an input that is a sum of two other inputs? simulate <- function( pulse1, pulse2 ) { # Define the time of simulation maxTime <- 6 dt <- 0.1 # Precision of simulation # Prepare variable for results of simulation ts <- seq(0,maxTime,dt) N <- length(ts) # Number of samples x <- numeric( N ) # The results will go here # Run the simulation x[1] <- 0 # Initial condition for( i in 2:N ) { # The input for the current time: if( ts[i] > 1 & ts[i] <= 2 ) { u <- pulse1 } else if( ts[i] > 3 & ts[i] <= 4 ) { u <- pulse2 } else { u <- 0 } # The dynamical system: DEFINED OUTSIDE THIS FUNCTION dx <- system( x[i-1], u ) # Numerical integration: x[i] <- x[i-1] + dt*dx } return( list( ts, x ) ) } # Define the dynamical system system <- function( x, u ) { -0.5 * x + u } # Simulate the dynamical system results <- simulate( 1, 0 ) # Store results for first pulse x1 <- results[[2]] # Repeat for second pulse results <- simulate( 0, 1 ) x2 <- results[[2]] # Repeat for both pulses results <- simulate( 1, 1 ) xboth <- results[[2]] # Compare xcalc <- x1 + x2 # Plot the results matplot( results[[1]], xboth, xlab = "Time", ylab = "x", type = "l",col="red",add = FALSE ) matplot( results[[1]], x1, xlab = "Time", ylab = "x", type = "l",col="blue",add = TRUE ) matplot( results[[1]], x2, xlab = "Time", ylab = "x", type = "l",col="green",add = TRUE ) matplot( results[[1]], xcalc, xlab = "Time", ylab = "x", type = "p",col="black",add = TRUE )