One solution might be to use global variables. Example with a simple counter:
function data = myFnc()
global data; % make it a global
if isempty(data) % not yet initialized
data = [];
end
i = 1;
while(i < 10)
pause(1)
disp(i)
data = [data, i];
i = i + 1;
end
Then on the command line, you have to do global data
once, and you can access the saved state. Quick test, I aborted the program with CTRL+C while it was running:
>> clear
>> clear global
>> x = myFnc();
1
2
3
4
Operation terminated by user during myFnc (line 10)
>> x
Undefined function or variable 'x'.
>> data
Undefined function or variable 'data'.
>> global data
>> data
data =
1 2 3 4
The use of global variables is usually not recommended, but on occasion they can be useful. I sometimes use globals to cache an expensive calculation so that it only has to computed once for every time I launch Matlab:
global data;
if isempty(data)
data = expensive_calculation();
end
For complex programs, there are probably cleaner ways to save some state from one iteration to another (implement some object?, pass a state object from one iteration to the next?, save to file?), but for some quick and dirty script, using globals is probably the easiest way.