How to make my program so when it hits a bug and spits out an error, the data is stored and the program can resume from its last location?

1 view (last 30 days)
Hi everyone
I am working on writing a modular program in which one master function calls several others. The program loads a structure of curves that are sequentially plotted and then fit manually by the user via ginput etc. The fit parameters etc of each curve are then stored in a structure, and these structures are finally made into substructures of a larger structure which is the desired output.
My problem is that there is currently a high likelihood of some type of runtime error, usually due to something such as receiving the wrong number of clicks during ginput. Whenever this happens, the program terminates and all of the output data is lost.
I would like to implement a means by which everything is saved on the fly, and if an error is encountered, the program discards the fit info from the current curve, reverts back to the previous curve, and continues without terminating. I think that simply trying again would eliminate the errors I am currently encountering, since they don't seem to occur consistently or repeatedly.
If there is a way to define a condition such as "if RUNTIME ERROR" ... then I would be able to tell the program to go back to the previous curve. I do not understand MATLAB well enough to know if this is possible, or if not, what alternative approaches are available.
I would be happy to provide more details if needed. Any suggestions or help are much appreciated!

Accepted Answer

Walter Roberson
Walter Roberson on 25 May 2011
You can use try/catch blocks.
  2 Comments
Rory Staunton
Rory Staunton on 25 May 2011
Thanks for the amazingly fast answer! I am looking into it now... So I am guessing I could put something like this (at least as a first attempt) in the loop:
for i=1:size(input,1)
for j=1:size(input,2)
try
output(i,j)=curvefit(input(i,j));
catch exception
j=j-1;
end
end
end
Would that work?
thx again
Walter Roberson
Walter Roberson on 25 May 2011
You cannot (meaningfully) change the value of a loop index variable, so you might have to rewrite that part as "while" loops. But the principle is sound.
Warning: do not call a variable "input" as that will conflict with the function of the same name.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!