There are many methods to obtain data from Matlab plots. Here I am going to show you a couple of them.
Method 1: Select data with “Brush/Select Data” Tool in GUI
After selecting the “Brush/Select Data” tool, hold down the left button and drag through the data you want to select. Then right click the mouse to select “Create Variable” and create variable you wants to name it.
It is very convenient and intuitive to do this way. The drawback of this method is that you would need a steady hand with mouse. If you are a script person, you might prefer writing a function to do it.
Method 2: Extract data with Matlab script
If you are using R2014a or older version, you can use some script like this (courtesy to this post from Mathworks):
1 2 3 4 5 6 7 8 |
h = gcf; %current figure handle axesObjs = get(h, 'Children'); %axes handles dataObjs = get(axesObjs, 'Children'); %handles to low-level graphics objects in axes objTypes = get(dataObjs, 'Type'); %type of low-level graphics object xdata = get(dataObjs, 'XData'); %data from low-level grahics objects ydata = get(dataObjs, 'YData'); zdata = get(dataObjs, 'ZData'); |
If you are using R2014b or newer version, the access to the graphical object become much easier. You could use this:
1 2 3 4 5 6 |
h = gcf ; axesObjs = h.Children(1) ; dataObjs = axesObjs.Children(1) ; xdata = dataObjs.XData ; ydata = dataObjs.YData ; zdata = dataObjs.ZData ; |
or simply something like this:
1 |
xdata = h.Children(1).Children(1).XData ; |
I am using MAtlab 2017a
I used the following code:
global xdata
global ydata
z=sin(1:100);
plot(z)
brush on
h = brush
axesObjs = h.Children(1) ;
dataObjs = axesObjs.Children(1) ;
xdata = dataObjs.XData ;
ydata = dataObjs.YData ;
zdata = dataObjs.ZData ;
but I get the error:
No appropriate method, property, or field ‘Children’ for class ‘matlab.graphics.interaction.internal.brush’.
Infact while trying it first I used the following, but xdata and ydata stored all the variables plotted already , I dont understand why
global xdata
global ydata
z=sin(1:100);
plot(z)
h = gcf ;
axesObjs = h.Children(1) ;
dataObjs = axesObjs.Children(1) ;
xdata = dataObjs.XData ;
ydata = dataObjs.YData ;
finally this worked for me
z=sin(1:100);
hLine=plot(z)
brush on
pause(5)
brushedIdx = logical(hLine.BrushData); % logical array
brushedXData = hLine.XData(brushedIdx);
brushedYData = hLine.YData(brushedIdx);