One technique to do this is to convert your for loops into while loops, like this:
if exist('recover.mat')
load('recover.mat');
else
I = 1;
J = 1;
K = 1;
end
while I <= max_I
while J <= max_J
while K =< max_K
do something
K = K + 1;
save recovery.mat
end
K = 1;
J = J + 1;
end
J = 1;
I = I + 1;
end
That is, instead of initializing the loop variables to 1 immediately like you would with
for I = 1 : max_I
for J = 1 : max_J
end
end
you continue on from whatever current values of I, J, K are active, and you do not reset those values until the end of the corresponding loop when you are setting up conditions for the next iteration of the enclosing loop.
If there is a failure, then the code should effectively end up restarting the computation from the beginning of the innermost loop iteration whose results were not already saved.
If some of the loops are short and fast you might not want to bother saving in the innermost, as saving takes time. You might, for example, want to move the save to after the J = J + 1, if the K loop is fast enough.