Any way get the filename into my print-command?

41 views (last 30 days)
I'm trying to print out a plot of some of my data, and i'm trying to have the name of the filename of my data, as the name of the picture i get of it. Is there any way to automatically(and maybe a little easy) do this? Short version of my script:
Data = importdata('FILENAME.txt');
t = Data.data(:,1);
dist = Data.data(:,2);
figure; plot(t,dist)
print(FILENAME,-dpng) % Trying to dynamically get the filename out, instead of having to manually change this
I'm very new to Matlab, so go easy on me ;)

Accepted Answer

Star Strider
Star Strider on 3 Oct 2015
If I understand your code correctly, I would use the file prefix, not the entire file name, to save the figure image, otherwise that risks problems. Also, unless FILENAME is a string, you have to put quotes around it as well. (I don’t use the print function often, so I’m relying on the documentation for guidance.) The fileparts function can be helpful in separating parts of the file name, making this easier.
  2 Comments
Anders Bennedsgaard
Anders Bennedsgaard on 3 Oct 2015
I'm not much into the whole string-part yet. As i mentioned, i'm new to Matlab.. But fileparts worked out for me, so thanks ! :)

Sign in to comment.

More Answers (1)

dpb
dpb on 3 Oct 2015
As you've written it, you're reading from 'FILENAME' as a fixed text string. You have all sorts of other options from having a list of filenames automatically generated by some sort of logic (often using a serial count) or reading them from a separate text file or by using a wild-card matching pattern in dir and then iterating over the resulting array d().name or letting the user select interactively with uigetfile which may be one or multiple files returned, your option.
After that, use whatever variable you choose for the file name and simply
title(filename)
will put that in the plot label.
[fn,path]=uigetfile('*.dat','Select file to process'); % select a file
Data=importdata(fullfile(path,fn)); % read it
...
title(['Experiment ' fn]) % put filename used on plot title
print(fn,'-dpng') % print to the filename w/ default extension
NB: must use string arguments in print with function form.

Categories

Find more on Printing and Saving in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!