Skip to content

Instantly share code, notes, and snippets.

@tomsherborne
Last active September 14, 2017 12:27
Show Gist options
  • Save tomsherborne/9a41cd9b9f202e07f03c42d85eef5dd7 to your computer and use it in GitHub Desktop.
Save tomsherborne/9a41cd9b9f202e07f03c42d85eef5dd7 to your computer and use it in GitHub Desktop.
Pulling data from a Matlab plot
h = findobj(gca,'Type','Line');
xd = get(h,'XData');
yd = get(h,'YData');
if iscell(xd) && iscell(yd) % Multi plot object
exprt = NaN*ones(length(yd{1}),length(yd)+1);
exprt(:,1) = xd{1};
for i = 1:length(yd)
exprt(:,i+1) = yd{i};
end
else % Single plot object
exprt = NaN*ones(length(yd),2);
exprt(:,1) = xd;
exprt(:,2) = yd;
end
dlmwrite('~/figdata.txt',exprt,'precision',6)
@tomsherborne
Copy link
Author

tomsherborne commented Sep 6, 2017

Primitive data extraction routine for retrieving a comma delimited .txt file of a MATLAB

Useful for pulling data from MATLAB for PGFplot or other LaTeX rendering packages
Works with plot(), semilogx(), semilogy() and other Cartesian format figures on at least R2015a, 2015b, 2016a

Usage

  • Run as a script or paste into the MATLAB console with the desired figure to extract as the current active figure (typically the last to be created).

Interpreting the output

  • The first column will be the x axis labels i.e. from plot(*x*,y)
  • The next columns will be the y axis data in the reverse order of the plot fn calls

Example:

figure();
plot(x,y1);
plot(x,y2);
plot(x,y3);

will be formatted as:

x, y3,y2,y1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment