0

I am unable to append to a numeric vector in R

y1 <- c()

euler <- function(f, y0, a, b, h)
{
  t <- a
  y <- y0
  while(t < b | isTRUE(all.equal(t, b))){
    t <- t + h
    y <- y + h*f(t, y)
    print(y)
    y1 <- c(y1, y)
  }
}

System_model <- function(y, t)
  return (y+t)

euler(System_model, 1, 0, 1, 0.1)

Expected: y1 has some values

Actual: y1 is empty

1 Answers1

0

The only thing you're missing is global assignment, since you're assigning inside a function (note the <<- in place of <-)

Also note that global assignment isn't always the best way to do things

y1 <- c()

euler <- function(f, y0, a, b, h)
{
  t <- a
  y <- y0
  while(t < b | isTRUE(all.equal(t, b))){
    t <- t + h
    y <- y + h*f(t, y)
    print(y)
    y1 <<- c(y1, y)
  }
}

System_model <- function(y, t)
  return (y+t)

euler(System_model, 1, 0, 1, 0.1)

Now y1 yields

> y1
 [1] 1.110000 1.241000 1.395100 1.574610 1.782071 2.020278 2.292306 2.601537 2.951690 3.346859 3.791545
stevec
  • 41,291
  • 27
  • 223
  • 311