Skip to content

Do not add class defaults to objects saved with saveobj - #414

Open
Enricoftw wants to merge 1 commit into
tbeu:masterfrom
Enricoftw:saveobj-no-defaults
Open

Enricoftw wants to merge 1 commit into
tbeu:masterfrom
Enricoftw:saveobj-no-defaults

Conversation

@Enricoftw

Copy link
Copy Markdown
Contributor

Objects whose saveobj method returns something other than an object of their class are read with the class defaults as extra fields next to any, so a program that reads such a field gets the default, not the value saved in any:

classdef SaveObjClass
    properties
        gain = 2;
        name = '';
    end
    methods
        function s = saveobj(obj)
            s.gain = obj.gain;
            s.name = obj.name;
        end
    end
    methods (Static)
        function obj = loadobj(s)
            obj = SaveObjClass;
            obj.gain = s.gain;
            obj.name = s.name;
        end
    end
end
obj_saveobj = SaveObjClass; obj_saveobj.gain = 5; obj_saveobj.name = 'motor';
save('test_saveobj_v7.mat', 'obj_saveobj', '-v7')

test_mat readvar test_saveobj_v7.mat obj_saveobj shows any.gain = 5 and next to it gain = 2. MATLAB R2022b and R2026b load gain = 5.

Since my #389 the defaults are read, but they only belong to objects from the normal property region. EnterFieldNameObject and GetFieldValueFromObject now skip them when the object uses a valid saveobj property set, the same check that GetPropertySetForObject makes. The test uses test_saveobj_v7.mat and test_saveobj_v73.mat from mat-io (BSD-3-Clause), attached here. Could you add them to matio_test_datasets? Until then the two new tests fail.

AI disclosure: I used Claude Code (Claude Opus 5.5) to find this, write the fix, the test and this description, and Codex (GPT-6 Astra and GPT-6.2 Sol), Claude Code (Claude Fable 5.2) and a second Claude Code (Claude Opus 5.5) session to review them. I understand what the PR does and why. I read and understood it before posting.

When saveobj returns something other than an object of its class, MATLAB
saves that value in the property any. EnterFieldNameObject and
GetFieldValueFromObject also added the class defaults as fields next to
any, so reading such an object showed gain 2 from the class defaults next
to the saved any.gain 5. Defaults are now skipped when the object uses a
valid saveobj property set, the same check that GetPropertySetForObject
makes.

The test reads test_saveobj_v7.mat and test_saveobj_v73.mat from mat-io
(BSD-3-Clause), which need to go into the test datasets.

Assisted-by: Claude Opus 5.5 <noreply@anthropic.com>
@Enricoftw

Copy link
Copy Markdown
Contributor Author

Test files:

test_saveobj.zip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant