MATLAB: Do I get an error if I reorder the fields in a MATLAB class object

MATLAB

I have created a class function named "testclass" that creates class object with differently ordered field names based on the input argument 'opt'. The code is as follows:
function cls = testclass(opt)
if(opt)
cls.a = 1;
cls.b = 2;
cls.c = 'hello';
else
cls.c = 'hello';
cls.b = 2;
cls.a = 1;
end
cls=class(cls,'testclass');
This function is placed in a folder named "@testclass".
Now, I execute the following statement:
c1 = testclass(1)
The output is given as:
c1 =
testclass object: 1-by-1
Then if I execute the following command,
c2 = testclass(0)
I receive the following error:
??? Error using ==> class
Field names and parent classes for class testclass cannot be changed
without clear classes.
Error in ==> testclass.testclass at 14
cls=class(cls,'testclass');
I did not change the field names or the number of fields in the class. All I changed was the order of the fields.

Best Answer

The ability to change the field ordering inside a class without invoking
clear classes
is not available in MATLAB. In fact, if the order of fields is changed, MATLAB interprets that the class function definition has been changed.
To work around this issue, issue the command
clear classes
before calling the CLASS function with reordered class fields.
An example to clear classes is given below:
c1 = testclass(1);
clear classes
c2 = testclass(0);