MATLAB: Matlab object assignment – copy an object instead of creating a pointer

MATLAB

Hi,
If I had an object variable and then assigned the same object to another variable, the latter acts as a pointer to the memory address of the original object instead of creating a copy of the original.
a = audioplayer(y, fs);
b = a;
set(b, 'SampleRate') = get(a, 'SampleRate') * 2;
play(a);
play(b);
In this example, a and b both have the same sample rate after the code is run. Is there any way to copy an entire object into a new variable instead of using a pointer to the memory address of the original object?

Best Answer

Actually, the default in matlab is that assignment creates a copy. Only classes that are explicitly defined as handle classes exhibit pointer behaviour. The audioplayer class is indeed a handle class, and so it has pointer behaviour.
Unfortunately for you, unless the class is customised to override the default copy behaviour there is no built-in way of copying the object. audioplayer is not customised, so you have to copy each property yourself. This can be automated thankfully:
function b = copyobj(a)
b = eval(class(a)); %create default object of the same class as a. one valid use of eval
for p = properties(a).' %copy all public properties
try %may fail if property is read-only
b.(p) = a.(p);
catch
warning('failed to copy property: %s', p);
end
end
end
The above could be refined to only copy read/write properties.