Matlab object assignment - copy an object instead of creating a pointer
Show older comments
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?
5 Comments
Jan
on 17 Nov 2016
The question is not clear.
Ryan Sinfield
on 17 Nov 2016
Jan
on 17 Nov 2016
Why do you want this behavior? What is the drawback in your case, that "b=a" does not duplicate the memory used for storing the signal? The standard behavior is efficient and saves processing time and memory. In addition it is not clear to me, what you exactly mean by "instead of using a pointer to the memory". Where do you think is a pointer used?
Guillaume
on 17 Nov 2016
The problem is:
a = instanceofhandleclass
a.prop1 = somevalue;
a.prop2 = someothervalue;
%... and so on, configure all properties of a
%now we want another object that is identical to a but for one property:
b = a; %not a copy due to shared memory
b.prop2 = somedifferentvalue; %also changes a.prop2!
If a is a value class (the default) then the b.prop2 = ... would trigger copy-on-write.
HiWave
on 22 Aug 2020
I second this....I have a structure of 20 classes I want to make a copy of to save the state before making changes. I can't do that unless I save a .mat file then load it later.
Accepted Answer
More Answers (0)
Categories
Find more on Variables in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!