store which iterations that the error took place

Hi everyone, I've been using try,catch and continue in my loop for any error. I was wondering is there any code that captures which iteration that error took place in the loop? so far I've put catch ME; disp(iter) to show me which iterations it is that the error took place but I can't capture them

 Réponse acceptée

Adam Danz
Adam Danz le 29 Août 2019
Modifié(e) : Adam Danz le 29 Août 2019
You could customize your own error message by basing it on the actual error message and appending the iteration number.
for i =1: 10
try
% [code that you don't trust :D]
catch ME
fprintf('%s Iteration #%d.\n', ME.message,i) %display error msg & iteration #
% or
error('%s Iteration #%d.', ME.message,i) %this will break the code
end
end

4 commentaires

JL
JL le 30 Août 2019
Thanks. possible to strore them the error iter values in a matrix?
I'm a bit puzzled by your question, you can do whatever you want in a catch statement, including storing whatever you want in whichever variable you want:
errorloopindex = NaN; %if still NaN, no error occured
for i = 1:Inf %some loop
try
%some code
catch ME
errorloopindex = i; %store loop index
warning('Error %s caught at index %d', Me.message, i)
end
end
badIterations = [];
for i =1: 10
try
% [code that you don't trust :D]
catch ME
badIterations(end+1) = i;
end
end
JL
JL le 30 Août 2019
Thanks Adam!

Connectez-vous pour commenter.

Plus de réponses (1)

KALYAN ACHARJYA
KALYAN ACHARJYA le 29 Août 2019
Modifié(e) : KALYAN ACHARJYA le 29 Août 2019
l=1;
error_iter=[];
for i=1:iter
% do operation
if error %error condition
error_iter(l)=iter
l=l+1;
end
end
error_iter

1 commentaire

JL
JL le 30 Août 2019
Thanks but It can't seem to work. I want to store each iterations value into a maxtrix

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Centre d'aide et File Exchange

Question posée :

JL
le 29 Août 2019

Commenté :

JL
le 30 Août 2019

Community Treasure Hunt

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

Start Hunting!

Translated by