Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Print to file with variable filename

375 views
Skip to first unread message

Helen

unread,
Feb 6, 2010, 10:54:06 AM2/6/10
to
This has to be something people do every day, and yet the documentation does not describe it correctly.

I want to save a figure to file with a variable file name (composed from a data group and a number). The following doesn't work because matlab reads 'filename' as a literal not a variable.

print '-pdf' filename

The documentation says to use the functional form and gives the following as an example:

print('-dpdf', filename)

Using this generates the matlab error

"??? Error using ==> print at 325
Handle input argument contains non-handle value(s).

Error in ==> printtest at 103
print('-dpdf', filename)"

Adding the handle reference 'gcf' (with or without quotes) gets the same error.

Rune Allnor

unread,
Feb 6, 2010, 11:20:50 AM2/6/10
to sl...@mathworks.com
On 6 Feb, 16:54, "Helen " <helenfrom...@gmail.com> wrote:
> This has to be something people do every day, and yet the documentation does not describe it correctly.  
>
> I want to save a figure to file with a variable file name (composed from a data group and a number).   The following doesn't work because matlab reads 'filename' as a literal not a variable.
>
> print '-pdf' filename
>
> The documentation says to use the functional form and gives the following as an example:
>
> print('-dpdf', filename)

This one works in R2006a:

plot(rand(10))
fname = 'test.pdf';
print(fname,'-dpdf')

If the example you state is verbatim from the docs, the
docs are flawed.

Rune

ImageAnalyst

unread,
Feb 6, 2010, 11:35:34 AM2/6/10
to
If you don't have a current graphics figure then it thinks that what
follows the dash is the handle to the figure. In other words I guess
it thinks dpdf is the name of a handle to a figure. But it's not, so
it bombs. What does it say in the command window when you say
whos gfc

Helen

unread,
Feb 6, 2010, 11:56:02 AM2/6/10
to
Hi Rune, and thanks for your reply.

I tried your suggestion but it didn't work. I am running 2009b which, to be honest, sucks badly compared to earlier versions. Here's a quote from the documentation:

"This example combines the previous two examples and uses the function form to print using both a handle variable and a file name variable:

h = figure; plot(1:4,5:8)
filename = 'mydata';
print(h, '-dpsc', filename)

This example works ONLY if you assign filename the literal value 'x'. If you try to assign it a text variable, the command fails with a reference to the handle.

I've also been disappointed with changes to plotting functions such as bar plots, which used to be fast and simple to get nice results just using the defaults. Text concatenation doesn't seem to work the way it used to. Documentation is badly written and unclear. My "outsource" detector is firing.

Rune Allnor <all...@tele.ntnu.no> wrote in message <51336523-3117-426c...@s12g2000yqj.googlegroups.com>...

Rune Allnor

unread,
Feb 6, 2010, 12:39:55 PM2/6/10
to
On 6 Feb, 17:56, "Helen " <helenfrom...@gmail.com> wrote:
> Hi Rune, and thanks for your reply.
>
> I tried your suggestion but it didn't work.   I am running 2009b which, to be honest, sucks badly compared to earlier versions.   Here's a quote from the documentation:  
>
> "This example combines the previous two examples and uses the function form to print using both a handle variable and a file name variable:
>
> h = figure; plot(1:4,5:8)
> filename = 'mydata';
> print(h, '-dpsc', filename)
>
> This example works ONLY if you assign filename the literal value 'x'.   If you try to assign it a text variable, the command fails with a reference to the handle.  

I'm not sure I undesrand: Matlab saves the file under tha *name*,
not the contents, of the variable?

Weird.

This one works under 2006a:

h = figure;
plot(1:4,5:8)

filename = sprintf('f%04d-%02d.pdf',1,2);
print(h, '-dpdf', filename)

Rune

us

unread,
Feb 6, 2010, 12:58:05 PM2/6/10
to
"Helen " <helenf...@gmail.com> wrote in message <hkk6v2$dvr$1...@fred.mathworks.com>...

> Hi Rune, and thanks for your reply.
>
> I tried your suggestion but it didn't work. I am running 2009b which, to be honest, sucks badly compared to earlier versions. Here's a quote from the documentation:
>
> "This example combines the previous two examples and uses the function form to print using both a handle variable and a file name variable:
>
> h = figure; plot(1:4,5:8)
> filename = 'mydata';
> print(h, '-dpsc', filename)
>
> This example works ONLY if you assign filename the literal value 'x'. If you try to assign it a text variable, the command fails with a reference to the handle.
>
> I've also been disappointed with changes to plotting functions such as bar plots, which used to be fast and simple to get nice results just using the defaults. Text concatenation doesn't seem to work the way it used to. Documentation is badly written and unclear. My "outsource" detector is firing.

your example works flawlessly on this r2009b(!)...
what does this yield in your system

which print -all;

us

Helen

unread,
Feb 6, 2010, 7:20:22 PM2/6/10
to
Thanks to ImageAnalyst and "us" for your help. I've narrowed it down to something about the text variable (never mind that the error message mentions the figure handle). So ... on my syste

This works:

h = figure(10)
plot(x,y)
fname = 'Bingo'
print(h, '-dpdf', fname)

>> fname
fname =
Bingo

And this also works:

h = figure(10)
plot(x,y)
filename = 'Bingo'
fname = filename;
print(h, '-dpdf', fname)

>> fname
fname =
Bingo

BUT THIS DOESN'T WORK:

h = figure(10)
plot(x,y)
namelist = textread('testfile','%s');
fname = namelist(1)
print(h, '-dpdf', fname)

>> fname
fname =
'Bingo'

So my text variable is wrong but I'm not sure how to fix it.

Thanks again,
Helen


"us " <u...@neurol.unizh.ch> wrote in message <hkkajd$jmp$1...@fred.mathworks.com>...

ImageAnalyst

unread,
Feb 6, 2010, 7:55:41 PM2/6/10
to
Helen:
Try using sprintf() and fullfile() to build up a proper filename.
By the way, is fname a character array, or a cell array?
-ImageAnalyst

Walter Roberson

unread,
Feb 6, 2010, 9:32:36 PM2/6/10
to
Helen wrote:

> BUT THIS DOESN'T WORK:
> h = figure(10)
> plot(x,y)
> namelist = textread('testfile','%s');
> fname = namelist(1)
> print(h, '-dpdf', fname)

namelist will be a cell array, so namelist(1) will be a 1x1 cell array.
If you want the contents of that array (the string), you need
fname = namelist{1}

Helen

unread,
Feb 8, 2010, 10:29:05 AM2/8/10
to
Thanks and to be honest I can't answer your question. The array is whatever "textread" creates. I can no longer count the number of 2007 scripts that are now broken. What happened to backward compatibility? For 12 years matlab worked easily and flawlessly over a wide range of conditions and purposes. Now it seems everything is broken. Wow. They even got rid of "nanmean". Or maybe I have to buy the $1000 stats package to get it? Sign me, "disappointed in Palo Alto".

ImageAnalyst <imagea...@mailinator.com> wrote in message <0bb51d64-ee63-4d81...@k22g2000vbp.googlegroups.com>...

Helen

unread,
Feb 8, 2010, 10:33:02 AM2/8/10
to
Thanks Walter. Not sure if this reflects another change-for-the-worse in matlab 2009 or perhaps an imperfect understanding of textread() I've had all along. I have scripts that treat its output like string vars and all worked nicely in the past. Oh well, thanks again and I assume this will fix it.

Regards,
Helen

Walter Roberson <robe...@hushmail.com> wrote in message <hkl8o4$qkd$1...@canopus.cc.umanitoba.ca>...

Steven Lord

unread,
Feb 8, 2010, 11:23:48 AM2/8/10
to

"Helen " <helenf...@gmail.com> wrote in message
news:hkk3at$8mo$1...@fred.mathworks.com...

> This has to be something people do every day, and yet the documentation
> does not describe it correctly.
> I want to save a figure to file with a variable file name (composed from a
> data group and a number). The following doesn't work because matlab
> reads 'filename' as a literal not a variable.
> print '-pdf' filename

That is correct. This is known as command-function duality -- you can call
most functions as though they were commands.

> The documentation says to use the functional form and gives the following
> as an example:
> print('-dpdf', filename)
>
> Using this generates the matlab error
>
> "??? Error using ==> print at 325
> Handle input argument contains non-handle value(s).
>
> Error in ==> printtest at 103
> print('-dpdf', filename)"
>
> Adding the handle reference 'gcf' (with or without quotes) gets the same
> error.

Looking at some of the later threads, I think I know what the problem is.
Set a breakpoint on line 103 of your printtest script/function (click on the
little line to the right of the line number in the Editor; you should see a
red dot appear on that little line.) Then run printtest, and when you see
the green arrow on that line go to the Command Window and type "whos
filename".

If you see the word "cell" in the Class column, then the problem is that
PRINT expects its inputs to be strings -- char arrays -- but you're passing
it a cell array containing a string. In that case, replace the line of
code:

print('-dpdf', filename)

with:

if iscell(filename)
print('-dpdf', filename{1});
else
print('-dpdf', filename);
end

That will call PRINT with the contents of the filename variable (if it is a
char array) or the contents of the first cell of the filename variable (if
it is a cell array.)

In any case, PRINT should display an error message that more clearly
indicates the cause of the problem when you pass a cell array in -- I will
enter that into our bug database.

--
Steve Lord
sl...@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ


Steven Lord

unread,
Feb 8, 2010, 11:28:43 AM2/8/10
to

"Helen " <helenf...@gmail.com> wrote in message
news:hkk6v2$dvr$1...@fred.mathworks.com...

> Hi Rune, and thanks for your reply.
> I tried your suggestion but it didn't work. I am running 2009b which, to
> be honest, sucks badly compared to earlier versions.

I am sorry to hear you feel that way. Are there particular problems (aside
from this one) that you've run into? If so, you should send your feedback
to Technical Support and/or your sales representative.

> Here's a quote from the documentation:
> "This example combines the previous two examples and uses the function
> form to print using both a handle variable and a file name variable:
>
> h = figure; plot(1:4,5:8)
> filename = 'mydata';
> print(h, '-dpsc', filename)
>
> This example works ONLY if you assign filename the literal value 'x'. If
> you try to assign it a text variable, the command fails with a reference
> to the handle.
> I've also been disappointed with changes to plotting functions such as bar
> plots, which used to be fast and simple to get nice results just using the
> defaults. Text concatenation doesn't seem to work the way it used to.
> Documentation is badly written and unclear. My "outsource" detector is
> firing.

I can assure you, we're not outsourcing. We do sometimes make changes that
we hope make our products more powerful, more usable, and/or more efficient
(and that sometimes is a trade-off for one of those considerations against
the others) -- again, if you feel that we haven't succeeded, please give us
your feedback on what you feel we should improve (and what you feel we've
done well.)

Steven Lord

unread,
Feb 8, 2010, 11:35:25 AM2/8/10
to

"Helen " <helenf...@gmail.com> wrote in message
news:hkpak1$q71$1...@fred.mathworks.com...

> Thanks and to be honest I can't answer your question. The array is
> whatever "textread" creates.

More than likely, in your situation, it's being returned as a cell array due
to the format of your file and/or the format specifier you're passing into
TEXTREAD.

> I can no longer count the number of 2007 scripts that are now broken.
> What happened to backward compatibility?

Backwards compatibility is still extremely important. If something that we
changed that broke your work, TELL US so that when or if we're considering
making a similar change in the future, we can take into account the fact
that we once broke backwards compatibility with a similar change when
determine whether to make thte change or how to inform users about the
change.

> For 12 years matlab worked easily and flawlessly over a wide range of
> conditions and purposes. Now it seems everything is broken. Wow.
> They even got rid of "nanmean". Or maybe I have to buy the $1000 stats
> package to get it? Sign me, "disappointed in Palo Alto".

NANMEAN is and has always been (well, at least as far back as I'm aware)
part of Statistics Toolbox.

http://www.mathworks.com/access/helpdesk/help/toolbox/stats/nanmean.html

Walter Roberson

unread,
Feb 8, 2010, 2:30:00 PM2/8/10
to
Helen wrote:
>I can no longer count the number of 2007
> scripts that are now broken. What happened to backward compatibility?
> For 12 years matlab worked easily and flawlessly over a wide range of
> conditions and purposes. Now it seems everything is broken. Wow.
> They even got rid of "nanmean". Or maybe I have to buy the $1000 stats
> package to get it? Sign me, "disappointed in Palo Alto".

The earliest reference that I can find to nanmean in this newsgroup is
December 27 2007, and it was referenced as being part of the stats toolbox then.

It appears you can get a free version of nanmean et al. from the Matlab File
Exchange,
http://www.mathworks.com/matlabcentral/fileexchange/6837

Walter Roberson

unread,
Feb 8, 2010, 3:14:33 PM2/8/10
to
Helen wrote:
> Thanks and to be honest I can't answer your question. The array is
> whatever "textread" creates. I can no longer count the number of 2007
> scripts that are now broken. What happened to backward compatibility?
> For 12 years matlab worked easily and flawlessly over a wide range of
> conditions and purposes. Now it seems everything is broken. Wow.

I haven't been able to trace it back any further, but the current behaviour of
textread() of producing a cell array of strings when the format element is
"%s", existed at least as early as Release 13 Service Pack 2 (6.5.2)
http://www.mathworks.com/access/helpdesk_r13/help/techdoc/ref/textread.html

textread() is not one of the functions listed as having changed between 6.1
and 6.5
http://www.mathworks.com/access/helpdesk_r13/help/base/relnotes/matlab/matlab1312.html

Release 6.1 was released in mid December 2001, more than 8 years ago, and 5
years before you started writing those 2007 scripts.


Possibly you have been accustomed to using the '%c' format element instead of
the '%s' format element.

Helen

unread,
Feb 8, 2010, 9:50:22 PM2/8/10
to
Thanks to Walter and everyone else who has replied. Thanks especially for your patience in the face of my crankiness. I will examine my old textread scripts and see if I can articulate precisely how their behavior appears to have changed. It seems that, yes, nanmean is also historically part of the stats toolbox. Fair enough.

My print command is now working and I appreciate everyone's helpful responses.

Regards,
helen

Walter Roberson <robe...@hushmail.com> wrote in message <hkprql$imm$1...@canopus.cc.umanitoba.ca>...

Pekka Kumpulainen

unread,
Feb 9, 2010, 3:30:22 AM2/9/10
to
"Helen " <helenf...@gmail.com> wrote in message <hkqihe$h6a$1...@fred.mathworks.com>...

> Thanks to Walter and everyone else who has replied. Thanks especially for your patience in the face of my crankiness. I will examine my old textread scripts and see if I can articulate precisely how their behavior appears to have changed. It seems that, yes, nanmean is also historically part of the stats toolbox. Fair enough.
>
> My print command is now working and I appreciate everyone's helpful responses.
>
> Regards,
> helen

Now if you are examining your old scripts you might want to get rid of all textread functions. Documentation of textread has suggested using textscan instead for years now, moving to more serious form of warning in each release.
In 2008b:
Note The textscan function is intended as a replacement for both textread and strread.

And in 2010a prerelease:
Note textread will be removed in a future version. Use textscan instead.

Yang

unread,
Apr 20, 2011, 2:37:05 PM4/20/11
to
Could you please show me the successful way of doing it? I saw a lot of replies and I got lost. Is there any example that can print a series of figures with a series of file names? Such as 'figure 1.bmp', 'figure 2.bmp', etc.

Thanks! I really can find such a basic example everywhere!

"Helen " <helenf...@gmail.com> wrote in message <hkqihe$h6a$1...@fred.mathworks.com>...

ImageAnalyst

unread,
Apr 20, 2011, 3:46:06 PM4/20/11
to
On Apr 20, 2:37 pm, "Yang " <yang-...@hotmail.com> wrote:
> Could you please show me the successful way of doing it? I saw a lot of replies and I got lost. Is there any example that can print a series of figures with a series of file names? Such as 'figure 1.bmp', 'figure 2.bmp', etc.
>
> Thanks! I really can find such a basic example everywhere!
>
----------------------------------------------------------------
Yang:
See the FAQ entries :
http://matlab.wikia.com/wiki/FAQ#How_do_I_save_my_figure.2C_axes.2C_or_image.3F_I.27m_having_trouble_with_the_built_in_MATLAB_functions.
and
http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F

Then do something like this (untested)

myFolder = 'C:\Documents and Settings\yourUserName\My Documents\My
Pictures';

for k = 1 : numberOfFiguresYouHave
h = figure(k); % Activate this figure.
baseFileName = sprintf('Figure %d.BMP', k);
fullFileName = fullfile(myFolder, baseFileName);
export_fig(fullFileName , h);
end

You may need to adapt the above.

Mark Chalmers

unread,
Apr 10, 2017, 7:12:10 AM4/10/17
to
I know this is an old issue but I had the same problem (r2016b) and spent over a day to find the solution, which I couldn't find in the forums. So here it is for the rest of you struggling with this frustration...

The problem occurs if the string variable you pass into the print function was built up of 'str' and 'char' data types it will not work and gives the error:

"Error using checkArgsForHandleToPrint
Handle input argument contains nonhandle values."

The solution is to convert all input variables to 'char' data types. (see example below)

% TestFolder = string('C:\MATLAB_Export'); % doesn't work
TestFolder = char('C:\MATLAB_Export'); % does work
FileID = 1;
FileName = sprintf('FileNo_%g',FileID);
ExportFile = strcat(TestFolder,'\',FileName);

x = 1:10;
y = x.^2;
f = figure;
plot(x,y);

print(f,ExportFile,'-dpng');

Saravanan Mani

unread,
Apr 10, 2017, 7:52:13 AM4/10/17
to
"Mark Chalmers" wrote in message <ocfpa4$rf3$1...@newscl01ah.mathworks.com>...
Dear Mark,

Can you try following code.

% TestFolder = string('C:\MATLAB_Export'); % doesn't work
TestFolder = 'C:\MATLAB_Export'; % does work
mkdir(TestFolder);
FileID = 1;
FileName = sprintf('FileNo_%g',FileID);
% ExportFile = strcat(TestFolder,'\',FileName);
x = 1:10;
y = x.^2;
f = figure;
plot(x,y);
print(f,[TestFolder '\' FileName],'-dpng');

Thanks & Regards,
Saravanan

Mark Chalmers

unread,
Apr 10, 2017, 11:01:08 AM4/10/17
to
"Saravanan Mani" wrote in message <ocfrl3$3ba$1...@newscl01ah.mathworks.com>...
Saravanan,

Your code is fine, but I'm not sure what you are trying to prove with it though.

TestFolder = 'C:\MATLAB_Export'; results in a 'char' data type, not a 'str'.
I wrote "char( 'C:\MATLAB_Export')" just to highlight the point.

The problem was never because the folder didn't exist, I had a check in there for that already.

I hope this clarifies the problem.

Best regards,
Mark.

Saravanan Mani

unread,
Apr 10, 2017, 12:29:13 PM4/10/17
to
"Mark Chalmers" wrote in message <ocg6nf$rkq$1...@newscl01ah.mathworks.com>...
Dear Mark,

See following example

>> a = char('Test')

a =

Test

>> b = 'Test'

b =

Test

>> whos a b
Name Size Bytes Class Attributes

a 1x4 8 char
b 1x4 8 char

A string is an array of characters. It is created by typing the characters within single quotes.
I hope above example is clear for you.

if you need more info about the folder is not exist, see below matlab help

>> help exist
>> help rmdir

if you need specific query about your concern please mail me saravana...@gmail.com

Thanks & Regards,
Saravanan

Mark Chalmers

unread,
Apr 12, 2017, 10:29:08 AM4/12/17
to
0 new messages