Clear Filters
Clear Filters

How to count number of times a sequence didn't converge in a for loop

3 views (last 30 days)
I'm writing a for loop, and each time the for loop runs I'm finding the mle using Matlab's inbuilt function. Sometimes the mle doesn't converge, and I want to introduce a counter to tell me how many times this happened. Something like "if converges, add 0, if not, add 1" kind of thing.

Answers (1)

Arnav Mendiratta
Arnav Mendiratta on 13 Jun 2017
As the foot note of mle function points out, with a poor starting point, the algorithm might converge to a local maxima instead of a global one or fail to converge at all. In case it does fail to converge, you will receive a warning
Warning: Maximum likelihood estimation did not converge. Iteration limit exceeded.
In such a case, you can not trust the results. You can, however, get the confidence levels of the estimated parameters if you use the function as:
[phat, pci] = mle(___,Name,Value)
If you see such a warning and you have Optimization toolbox, you can use the 'OptimFun' name value pair to use 'fmincon' as the optimization function. You can then change the maximum number of iterations ('MaxIter') and step of derivative ('DerivStep') to make sure the algorithms reaches an optima. By default, the mle function uses the following settings:
>> statset('mlecustom')
ans =
struct with fields:
Display: 'off'
MaxFunEvals: 400
MaxIter: 200
TolBnd: 1.0000e-06
TolFun: 1.0000e-06
TolTypeFun: []
TolX: 1.0000e-06
TolTypeX: []
GradObj: 'off'
Jacobian: []
DerivStep: 6.0555e-06
FunValCheck: 'on'
Robust: []
RobustWgtFun: []
WgtFun: []
Tune: []
UseParallel: []
UseSubstreams: []
Streams: {}
OutputFcn: []
Of course, this does not point out the exact number of iterations taken to converge to a parameter estimate.
If this warning occurred, this means that the function wasn't able to converge and you can find the warning ID using "lastwarn".
Warning: Maximum likelihood estimation did not converge. Iteration
limit exceeded.
> In mlecustom (line 241)
In mle (line 239)
In FitRicianDistributionwithKnownScaleParameterExample (line 18)
>> [msgStr,msgId] = lastwarn
msgStr =
'Maximum likelihood estimation did not converge. Iteration limit exceeded.'
msgId =
Now if you have this warning, you can implement something that identifies if the algorithm did not converge and then add 0 or 1 based on your use case. This post has some discussion on how to achieve this.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!