MATLAB: Detection of Ctrl+C in M file

ctrl+cdetectionfunctionMATLAB

Hi everyone
I want to detect when somebody press "Ctrl C". How can I be detected it while an function is be running . if I do that , I will save some of variables to workspace.

Best Answer

Ilkay - you can try the following which is taken from Loren Shure's blog entry Keeping Things Tidy. It makes use of the onCleanup function which will perform "cleanup" tasks upon function completion or termination.
Suppose you have some function that does some work in a while or for loop which may take so long that the user becomes impatient and presses the ctrl+c to cancel out of the function. Within that function, we define a clean up function to fire when our main function/program terminates
function someFunction
% create our clean up object
cleanupObj = onCleanup(@cleanMeUp);
% load an image, create some variables
I = imread('someImage.jpg');
Z = zeros(42,24,42);
U = ones(1,2,3);
keepGoing = true;
while keepGoing
% do our work
% add a 100 msec pause
pause(0.01);
end
% fires when main function terminates
function cleanMeUp()
% saves data to file (or could save to workspace)
fprintf('saving variables to file...\n');
filename = [datestr(now,'yyyy-mm-dd_HHMMSS') '.mat'];
save(filename,'I','Z','U');
end
end
I tried the above on MATLAB R2014a (Mac OS X 10.8.5) and it would respond to the pressing of ctrl+c - firing the cleanMeUp function before terminating. Of course, that same function will fire if the program terminates regularly (i.e. if some exit condition is met and the code exits the while loop gracefully).