David Z
David Z

Reputation: 7041

Repeat a loop for convergence

I have a 4-step computation and want to repeat the 2-3 steps until convergence. Here is an example:

muh<-t(rnorm(4))
muk<-t(rnorm(4))
Sigmah<-matrix(rnorm(16),4,4)
Sigmak<-matrix(rnorm(16),4,4)
nh<-nk<-25

step1

  muw<-(nh*solve(Sigmah)+nk*solve(Sigmak))^(-1)
    %*%(nh*solve(Sigmah)%*%t(muh)+nk*solve(Sigmak)%*%t(muk))

step2

Sigmahw<-Sigmah+(t(muh)-muw)%*%t(t(muh)-muw)
Sigmakw<-Sigmak+(t(muk)-muw)%*%t(t(muk)-muw)

step3

 muw<-(nh*solve(Sigmahw)+nk*solve(Sigmakw))^(-1)
    %*%(nh*solve(Sigmahw)%*%t(muh)+nk*solve(Sigmakw)%*%t(muk))

How can I repeat step2 and step3 until Sigmahw and Sigmakw convergence?

Upvotes: 0

Views: 1106

Answers (2)

nil
nil

Reputation: 151

muh<-t(rnorm(4))
muk<-t(rnorm(4))
Sigmah<-matrix(rnorm(16),4,4)
Sigmak<-matrix(rnorm(16),4,4)
nh<-nk<-25

threshold <- 0.1
muw<-(nh*solve(Sigmah)+nk*solve(Sigmak))^(-1)%*%(nh*solve(Sigmah)%*%t(muh)+nk*solve(Sigmak)%*%t(muk))
Sigmahw<-Sigmah+(t(muh)-muw)%*%t(t(muh)-muw)
Sigmakw<-Sigmak+(t(muk)-muw)%*%t(t(muk)-muw)
repeat {
    lastSigmahw <- Sigmahw
    lastSigmakw <- Sigmakw
    muw<-(nh*solve(Sigmahw)+nk*solve(Sigmakw))^(-1)%*%(nh*solve(Sigmahw)%*%t(muh)+nk*solve(Sigmakw)%*%t(muk))
    Sigmahw<-Sigmah+(t(muh)-muw)%*%t(t(muh)-muw)
    Sigmakw<-Sigmak+(t(muk)-muw)%*%t(t(muk)-muw)
    difference <-
        norm(Sigmahw - lastSigmahw, type='F') +
        norm(Sigmakw - lastSigmakw, type='F')
    if (difference  < threshold) {
        break
    }
}

Your code doesn't converge actually for the several times I ran it though, make sure your equations are right.

Upvotes: 2

Julien Marrec
Julien Marrec

Reputation: 11895

Use a repeat statement and check for a condition using if

repeat{
  statements...
  if(condition){
    break
  }
}

You can also use a while statement

See R documentation : http://cran.r-project.org/doc/manuals/R-lang.html#while

Upvotes: 1

Related Questions