[R] Centered difference operation on matrix with R

Pascal Oettli kridox at ymail.com
Wed Apr 2 04:01:33 CEST 2014

```Dear list members,

Regards,
Pascal Oettli

On Fri, Mar 28, 2014 at 2:51 PM, Pascal Oettli <kridox at ymail.com> wrote:
> Dear list members,
>
> I am wondering whether there is any more efficient way to calculate
> centered difference on matrix in R? Please see herewith an example:
>
> lon <- matrix(rep(seq(0,2,length.out=1e3), 1e3), 1e3, 1e3)
> lat <- matrix(rep(seq(0,2,length.out=1e3), each=1e3), 1e3, 1e3)
> x <- matrix(rep(seq(0.01,2,length.out=1e3), 1e3), 1e3, 1e3)
> y <- matrix(rep(seq(0.01,2,length.out=1e3), each=1e3), 1e3, 1e3)
> u <- y * cos(x)
> v <- y * sin(x)
>
> dx <- diff(lon,2); dx <- rbind(NA,dx,NA); dx <- dx*to.rad
> dy <- t(diff(t(lat),2)); dy <- cbind(NA,dy,NA); dy <- dy*to.rad
>
> du <- t(diff(t(u * cos(lat*to.rad)),2)); du <- cbind(NA,du,NA)
> dv <- diff(v,2); dv <- rbind(NA,dv,NA)
>
> Best Regards,
> Pascal Oettli

--
Pascal Oettli
Project Scientist
JAMSTEC
Yokohama, Japan

```