MATLAB: Is it possible to conditionally save an object using the SAVEOBJ method in MATLAB 7.7 (R2008b)

MATLAB

In the following class definition file I am trying to create an object that can be conditionally saved using the SAVEOBJ method.
classdef myobj
properties
val = 1;
end
methods
function obj = myobj(in)
obj.val = in;
end
function obj = saveobj(obj)
if obj.val~=1
error ('Save aborted')
else
disp('Saving object.');
end
end
end
end
I try to create and save an object as follows:
a = myobj(2);
save('savefile.mat','a')
But when the control reaches the saveobj method, my expected error is thrown as a warning:
Warning: Error saving an object of class 'myobj':
Error using ==> myobj>myobj.saveobj at 15
Save aborted
and the MAT file is created anyway.

Best Answer

In the current MATLAB implementation it is not possible to disable saving of an object through SAVEOBJ. MATLAB creates the MAT file as soon as the control comes to SAVEOBJ with the current state of the object. We can modify the object fields by assigning new values in the SAVEOBJ method.
A workaround is to create a wrapper function and call SAVEOBJ after the conditional check. In the example given above, replace the SAVEOBJ method with the following two methods MYSAVE and SAVEOBJ:
function mysave(filename,obj)
% Only allow save if obj.val == 1
if obj.val ~= 1
error('Wrong value in object. Not saving.');
else
% Rename the object
objname = inputname(2);
eval([objname '= obj;']);
save(filename,objname);
end
end
function obj = saveobj(obj)
disp('Saving object.');
end
One can now execute the following code to save the object under different conditions.
1) When the save should be successful:
a = myobj(1);
mysave('savefile1.mat',a);
Saving object.
2) When the save should fail:
b = myobj(2);
mysave('savefile2.mat',b);
??? Error using ==> myobj>myobj.mysave
at 14
Wrong value in object. Not saving.