Return an output even if the while loop gets an error
17 次查看(过去 30 天)
显示 更早的评论
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
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.
回答(1 个)
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!