Hi,
set.seed(49)
X = matrix(rnorm(100), 10, 10)
X1<- X
result<-0
for(m in 1:nrow(X)){ for(n in 1:ncol(X)){ if(X[m,n] != 0){ result
= result + (X[m,n] / (1 + abs(m - n))) } }}
indx<-which(X!=0,arr.ind=TRUE)
indx1<-1+abs(indx[,1]-indx[,2])
X1[indx]<- X1[indx]/indx1
#or
re
Hi,
set.seed(49)
X = matrix(rnorm(100), 10, 10)
X1<- X
result<-0
for(m in 1:nrow(X)){ for(n in 1:ncol(X)){ if(X[m,n] != 0){ result
= result + (X[m,n] / (1 + abs(m - n))) } }}
indx<-which(X!=0,arr.ind=TRUE)
indx1<-1+abs(indx[,1]-indx[,2])
X1[indx]<- X1[indx]/indx1
#or
Thank you for your answer. This is what I needed.
> From: s.elli...@lgcgroup.com
> To: r-help@r-project.org
> Date: Fri, 4 Oct 2013 15:13:49 +0100
> Subject: Re: [R] Trying to avoid nested loop
>
>
> > I'm trying to avoid using nested loops in the following cod
> I'm trying to avoid using nested loops in the following code but I'm
> not sure how to proceed. Any help would be greatly appreciated.
> With regards,Phil
> X = matrix(rnorm(100), 10, 10)
> result = 0
> for(m in 1:nrow(X)){
> for(n in 1:ncol(X)){
> if(X[m,n] != 0){
4 matches
Mail list logo