MATLAB Answers

Return an output even if the while loop gets an error

10 ビュー (過去 30 日間)
End_Mzz
End_Mzz 2019 年 6 月 25 日
コメント済み: End_Mzz 2019 年 6 月 26 日
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);
H(:,:,1)=V;
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);
%display(model_fwd_vol)
% compute new LV parameters
V = V ./ model_fwd_vol .* mkt_fwd_vol;
H(:,:,nb_iter)=V;
end
MaxErr = MaxErr(2:nb_iter);
end

  2 件のコメント

Adam
Adam 2019 年 6 月 25 日
doc try catch
can help do this if you just wrap up the whole thing in a try-catch block and put a return statement in the catch.
I wouldn't recommend it, but it will return from the function at least. Although if the error is before H is declared then it still won't be returned unless you declare it as empty (or whatever default you wish) right at the start.
End_Mzz
End_Mzz 2019 年 6 月 26 日
Thank you, it works and get the job done! So for now it is ok!
Thanks again!

サインインしてコメントする。

回答 (1 件)

Pullak Barik
Pullak Barik 2019 年 6 月 25 日
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

  1 件のコメント

End_Mzz
End_Mzz 2019 年 6 月 26 日
Thank you so much!

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by