# Restart iteration in a for loop when an error is thrown

**URL:** <https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850>\
**Category:** General Usage\
**Tags:** error, loops\
**Created:** [July 29, 2020, 12:45am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850 "2020-07-29T00:45:02Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [July 29, 2020, 12:45am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/1 "2020-07-29T00:45:02Z")

</div>

I have to run a `for` loop based on random numbers generation and inversion of a matrix. When the matrix is singular, my code stops, throwing a `SingularException()` error. If this occurs at a certain iteration of the loop, how can I force the code to restart again the iteration with new numbers generation until a regular matrix is found to continue the loop until the end?

To keep it simple, suppose the following code:

```julia
res=zeros(500)
for i=1:length(res) 
    X=rand(100,100)
    X2=transpose(X)*X
    res[i]=tr(inv(X2))
end

```

If at iteration `i` the matrix `X2` is singular, how can I run again iteration `i` until the iteration can be completed and then proceed with the loop?

---

<div class="post-metadata">

**Author:** ![tomerarnon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tomerarnon/32/3170_2.png) [@tomerarnon](https://discourse.julialang.org/u/tomerarnon)\
**Post date:** [July 29, 2020, 12:46am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/2 "2020-07-29T00:46:08Z")

</div>

I think you would have to use a `while` loop instead, with a condition on incrementing `i`.

---

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [July 29, 2020, 12:53am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/3 "2020-07-29T00:53:50Z")

</div>

Ok, I’ll try your solution 😉

---

<div class="post-metadata">

**Author:** ![Duane\_Wilson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/duane_wilson/32/9506_2.png) [@Duane\_Wilson](https://discourse.julialang.org/u/Duane_Wilson)\
**Post date:** [July 29, 2020, 1:48am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/4 "2020-07-29T01:48:06Z")

</div>

Another possible option is to put the body of the loop into a function and wrap it in a `try ... catch` block. If an exception is found you call the function again.

So something like:

```julia
function my_inner_loop()
   try
      X=rand(100,100)
      X2=transpose(X)*X
      return tr(inv(X2))
   catch
      my_inner_loop()
   end
end

```

---

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [July 29, 2020, 1:54am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/5 "2020-07-29T01:54:50Z")

</div>

Do I have to call manually the function if an exception is found? Because I want to let the loop running alone in background even when my PC is off.

---

<div class="post-metadata">

**Author:** ![a5vzener](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/a5vzener/32/16257_2.png) [@a5vzener](https://discourse.julialang.org/u/a5vzener)\
**Post date:** [July 29, 2020, 3:37am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/6 "2020-07-29T03:37:51Z")

</div>

I think you could do something like this:

```julia
    i = 0

function my_inner_loop(;maxtries=100)
    while i < maxtries
        try
          X=rand(100,100)
          X2=transpose(X)*X
          r = tr(inv(X2))
          return r
        catch
          i += 1
          my_inner_loop()
        end
   end
   return nothing # or 0 or whatever makes sense
end

```

---

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [July 29, 2020, 3:44am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/7 "2020-07-29T03:44:26Z")

</div>

Ok, thanks! I’ll try this solution too 🙂 How do I call the function?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [July 29, 2020, 8:44am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/8 "2020-07-29T08:44:41Z")

</div>

I would suggest that you do a QR decomposition of X = QR, so that X'X = R'R, use that to detect invertibility and just return `Inf` for singular matrices, then work with `Rinv = inv(R)` etc.

Alternatively, if you are willing to use an SVD,

```julia
sum(x -> abs2(1/x), svd(X).S)

```

is equivalent to `tr(inv(X'*X))` because of [similarity invariance](https://en.wikipedia.org/wiki/Trace_(linear_algebra)#Similarity_invariance).

---

<div class="post-metadata">

**Author:** ![a5vzener](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/a5vzener/32/16257_2.png) [@a5vzener](https://discourse.julialang.org/u/a5vzener)\
**Post date:** [July 29, 2020, 2:18pm UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/9 "2020-07-29T14:18:27Z")

</div>

After posting the above I realized that there are some scoping issues with the variables. The following code might be closer to what you want for the non-math part:

```julia
function my_outerspace_loop(maxtries=100)

    i = 1
    result = nothing
    function my_inner_loop(max)
        # global i
        while i < maxtries
            @show i
            try
                X=rand(100,100)
                X[1,1] < 0.1 || throw()
                X2=transpose(X)*X
                result = tr(inv(X2))
                break
            catch
                println("Trying again...")
                i += 1
                return my_inner_loop(max)
            end
       end
       return (result, i) # or 0 or whatever makes sense
    end

    my_inner_loop(maxtries)
end

```

---

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [July 29, 2020, 11:47pm UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/10 "2020-07-29T23:47:52Z")

</div>

Thank you for your suggestion 😉 But I really want to know how to restart an iteration. That’s my central problem.

---

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [July 29, 2020, 11:49pm UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/11 "2020-07-29T23:49:53Z")

</div>

Thanks. But how can I call this function? `my_inner_loop(1)` or `my_inner_loop()` with any number inside `()`?

---

<div class="post-metadata">

**Author:** ![a5vzener](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/a5vzener/32/16257_2.png) [@a5vzener](https://discourse.julialang.org/u/a5vzener)\
**Post date:** [July 30, 2020, 1:53am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/12 "2020-07-30T01:53:44Z")

</div>

> [@a5vzener](#):
>
> ```julia
> function my_outerspace_loop(maxtries=100)
> 
> i = 1
> result = nothing
> function my_inner_loop(max)
> # global i
> while i < maxtries
> @show i
> try
> X=rand(100,100)
> X[1,1] < 0.1 || throw()
> X2=transpose(X)*X
> result = tr(inv(X2))
> break
> catch
> println("Trying again...")
> i += 1
> return my_inner_loop(max)
> end
> end
> return (result, i) # or 0 or whatever makes sense
> end
> 
> my_inner_loop(maxtries)
> end
> 
> ```

In this case you would call `my_outerspace_loop(n)` where n is the maximum number of times you want to allow your algorithm to try to find an appropriate solution. You do not call `my_inner_loop` directly.

Is that what you meant by “how to call”?

---

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [July 30, 2020, 2:11am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/13 "2020-07-30T02:11:15Z")

</div>

Yes, that’s what I mean! Thank you! I’ll apply your method!

---

<div class="post-metadata">

**Author:** ![a5vzener](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/a5vzener/32/16257_2.png) [@a5vzener](https://discourse.julialang.org/u/a5vzener)\
**Post date:** [July 30, 2020, 2:45am UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/14 "2020-07-30T02:45:12Z")

</div>

> [@a5vzener](#):
>
> `X[1,1] < 0.1 || throw()`

I accidentally left in some testing stuff. Don’t forget to comment out `X[1,1] < 0.1 || throw()` or you’ll never get anywhere in life.

---

<div class="post-metadata">

**Author:** ![sergevic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sergevic/32/9958_2.png) [@sergevic](https://discourse.julialang.org/u/sergevic)\
**Post date:** [September 10, 2020, 4:36pm UTC](https://discourse.julialang.org/t/restart-iteration-in-a-for-loop-when-an-error-is-thrown/43850/15 "2020-09-10T16:36:17Z")

</div>

Ok, perfect!
