# [R] Iterative loop using "repeat"

Jim Lemon jim at bitwrit.com.au
Sat Jan 5 05:55:54 CET 2013

```On 01/04/2013 10:13 PM, mary wrote:
> Hi,
> I'm Marianna
> I'm trying to apply the command "repeat" to my matrix but the repeat process
> doesn't work as I would.
>
> In particular I would like to apply the function robustm () _that I have
> created_ to my two matrices,  if the difference between the two matrices is
> less than 0.001, R give me back the last matrix.
> The code thus created allows me to repeat the process only on the first two
> matrices:
>
> function(x) {
> for(i in 1:10)
> repeat {
> b<-robustm(S_X)
> b2<-robustm(b)
> if(abs(b2[i,i]-b[i,i])<=0.001)
> break
> }
> print(b2)}
>
> in particular S_X is my matrix number1 (already defined, dim 10*10), b2 is
> my matrix n.2, if the difference isn't less than my value, I would like
> reiterate the process using b2 instead S_X and so on...
>
> (actually serves to me that if the difference is not less than 0.001 the
> process starts again taking the last array that has identified as output (in
> this case b2) and the remarket in the process creating b3, b4, etc. up to
> find the minimum difference between the two matrices and returns me the
> last.)
>
Hi Mary,
In the above, you are testing whether there is at least one absolute
difference less than or equal to 0.001 in the diagonals of two matrices.
One matrix is S_X after applying the "robustm" function and the other is
after a second iteration of "robustm" on the first matrix. So it seems
that "robustm" is a function that hopefully converges on some final value.

First, remember that applying "robustm" to S_X in your repeat loop
doesn't change S_X. Each time you repeat, you will get the same result.
What you may want to do is this:

iterate.robustm<-function(x) {
b<-robustm(x)
finido<-FALSE
while(!finido) {
b2<-robustm(b)
for(i in 1:10)
if(abs(b2[i,i]-b[i,i])<=0.001) finido<-TRUE
b<-b2
}
return(b2)
}

iterate.robustm(S_X)

This iterates "robustm" until at least one diagonal difference is less
than or equal to 0.001. Hopefully that function will always converge.

Jim

```