Any way get the filename into my print-command?

20 次查看(过去 30 天)
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 ;)

采纳的回答

Star Strider
Star Strider 2015-10-3
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 个评论
Anders Bennedsgaard
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 ! :)

请先登录,再进行评论。

更多回答(1 个)

dpb
dpb 2015-10-3
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.

类别

Help CenterFile Exchange 中查找有关 Printing and Saving 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by