Replace Remote MATLAB Object
Is it possible to change the string after deleting it using the properties previously obtained by the get () method.
For example:
% Create the plot and 'get' its properties.
axes
P = plot(1:360, sind(1:360));
PG = get(P);
% Delete the plot.
delete(P)
% Replot the line...
plot(PG) % ?????
I would like this to be generalizable i.e. the solution will work for surface plots, line plots, text annotations, etc.
source to share
Approach 1: don't delete it, make it invisible
Instead of deleting and recreating the object, you can make it invisible:
set(P, 'visible', 'off')
and then visible again
set(P, 'visible', 'on')
Approach 2: Create an object and set property values โโusing a loop
If you really want to recreate the deleted object, you can proceed as follows: create an object of the same type and use a loop for
to set its properties to the stored values. Block - Required because some properties are read-only and cause an error. try
catch
%// Replot the object...
Q = plot(NaN); %// create object. Plot any value
fields = fieldnames(PG);
for n = 1:numel(fields)
try
set(Q, fields{n}, getfield(PG, fields{n})); %// set field
catch
end
end
You can use this approach with other types of graphic objects, for example surf
, but then you need to change the line that creates the object (first line in the code above). For example, with surf
this it will be something like
Q = surf(NaN(2)); %// create object. surf needs matrix input
I tested this in R2010b with plot
and surf
.
Approach 3: Make a copy of the object and restore it using copyobj
Use copyobj
to make a copy of an object in another (possibly invisible) shape and then restore it. This works automatically for any type of object.
%// Create the plot
P = plot(1:360, sind(1:360));
a = gca; %// get handle to axes
%// Make a copy in another figure
f_save = figure('visible','off');
a_save = gca;
P_saved = copyobj(P, a_save);
%// Delete the object
delete(P)
%// Recover it from the copy
P_recovered = copyobj(P_saved, a);
source to share
You can just save the object as a struct PG
using the command get
(as you already did) and then set all the parameters at once using the command set
. There are several read-only fields that must be removed before setting them up, and the objects must be of the same type. In the following example, we create a graph with plot(0)
that is overwritten with data from the previous graph.
% Create the plot
figure
P = plot(1:360, sind(1:360));
% Store plot object
PG = get(P);
% Delete the plot
delete(P);
% Remove read-only fields of plot object
PG = rmfield(PG,{'Annotation','BeingDeleted','Parent','Type'});
% Create a new plot
figure
P = plot(0);
% Set the parameters
set(P,PG);
If you don't want to manually delete fields, use try-catch
-block and iterate over all fields as described in Luis Mendo's answer.
source to share