MATLAB Answers

Return an output even if the while loop gets an error

10 views (last 30 days)
End_Mzz on 25 Jun 2019
Commented: End_Mzz on 26 Jun 2019
This is the function I am using with other functions inside (this is not important anyway).
What I would like to do is to have as output all the matrix V (V = V ./ model_fwd_vol .* mkt_fwd_vol) at all iterations (I decided to use a 3d matrix that at each index has got the matrix V, I could have also used lists but since at every iteration the matrix V has the same dimension, I preferred the former way).
The point is that if the while loop end without error then I get as output the 3d matrix H with all the matrices V at all iterations and I am fine with it, but as soon as I get an error inside the while loop I don't have H as an output anymore, but I would like to have it in any case even if the iterations did not completed and an error occur.
I hope what I have written is understandable and thank you in advance.
function [V, ModelVol, MaxErr, H] = calibrator(T,K_norm,MktVol,MaxIter,N,M,K_min,K_max,Scheme)
nb_iter = 1;
MaxErr(nb_iter) = 100;
% initial guess for the LV matrix
V = MktVol;
% forward market volatility
mkt_fwd_vol = fwd_from_spot_vol(T,MktVol);
while ( nb_iter < MaxIter )
% update iteration number
nb_iter = nb_iter+1;
% compute model implied volatilities
ModelVol = model_volatility(T,K_norm,V,N,M,K_min,K_max,Scheme);
% compute max_err
MaxErr(nb_iter) = max(max(abs(ModelVol-MktVol)));
% compute model fwd vol
model_fwd_vol = fwd_from_spot_vol(T,ModelVol);
% compute new LV parameters
V = V ./ model_fwd_vol .* mkt_fwd_vol;
MaxErr = MaxErr(2:nb_iter);
End_Mzz on 26 Jun 2019
Thank you, it works and get the job done! So for now it is ok!
Thanks again!

Sign in to comment.

Answers (1)

Pullak Barik
Pullak Barik on 25 Jun 2019
I suggest that you use try-catch blocks in your code to customise the behaviour when you get an error.
Link to documentation- Try-Catch

Community Treasure Hunt

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

Start Hunting!