I have something like this:
p = plot([0 1], [0 1], [1 2], [1 2]);
I want to take each pair and append another number.
x = get(p, 'XData');
y = get(p, 'YData');
x1 = mat2cell([x{1} double(2)]);
y1 = mat2cell([y{1} double(2)]);
x2 = mat2cell([x{2} double(3)]);
y2 = mat2cell([y{2} double(3)]);
set(p, 'XData', [x1; x2], 'YData', [y1; y2]); % this does not work
drawnow;
'get' is giving me some data in a format and I am 'set'-ing back in the same format the data with one more value for each pair.
The error I get is: Conversion to double from cell is not possible.
There are a number of different ways to fetch the current plot points and add to them. The first two lines of Eitan's answer (using cellfun
) are one way. Here's one using cell2mat
and num2cell
:
newX = [2 3]; % New x values to add
newY = [2 3]; % New y values to add
X = num2cell([cell2mat(get(p,'XData')) newX(:)], 2);
Y = num2cell([cell2mat(get(p,'YData')) newY(:)], 2);
The key issue to note when using the set
function on multiple handles is stated in this excerpt from the documentation:
set(H,pn,MxN_pv) sets n property values on each of m graphics objects, where m = length(H) and n is equal to the number of property names contained in the cell array pn. This allows you to set a given group of properties to different values on each object.
As a result, your single call to set
has to look like this:
set(p, {'XData'}, X, {'YData'}, Y);
Note that length(p)
is equal to 2, the property strings are placed in cell arrays, and X
and Y
are each 2-by-1 cell arrays.