Return an output even if the while loop gets an error
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Adam
am 25 Jun. 2019
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.
Antworten (1)
Pullak Barik
am 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
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!