views:

74

answers:

1

Hey guys. I have some difficulty in creating a filename. okay, here is what I want to do: a matlab function called file_save(filename,input_data) is to save data into a xml file. so in a for loop, I want to create xml file with sequential filename eg. output1.xml output2.xml output3.xml

I guess there are some way of combining filename? Can anybody give me some help?

Thanks!

+2  A: 

You can concatenate strings the same way as arrays in MATLAB. (Actually, strings are treated like character arrays.)

For file #n,

name='MyFile';
ext='.xml';
filename=[name,num2str(n),ext];

should get you what you want.

As @Andrew points out in the comments, you can also use sprintf to format the filename:

filename = sprintf('MyFile%0*d.xml', ceil(log10(N+1)), n);

where N is the total number of files you plan on naming, and n is your current iteration. The ceil(log10(N+1)) gets you the number of digits you need for correct leading zero-padding.

@Azim points out that num2str can accomplish the same thing:

filename=[name,num2str(n,['%0' num2str(ceil(log10(N+1))),'d']),ext];
Doresoom
I think you meant num2str(n)
Marm0t
Yes you are right, Marm0t. num2str(n) is correct. Thanks, you two!
appi
Whoops, thanks for the edit!
Doresoom
You can also use sprintf, like "filename=sprintf('MyFile%02d.xml', n)". This has the advantage of left-padding the numbers with zeros so the file names collate alphabetically in the order of increasing n.
Andrew Janke
@Andrew left padding zeros can also be acheived with num2str(n,'%03d'). As in filename=[name,'_',num2str(n,'%03d'),ext];
Azim
@Azim: That's awesome, I had no idea you could do that with num2str!
Doresoom
@Doresoom, Just recently learned that little trick myself. Thanks
Azim
@Azim - Nice. Let's go even further. The sprintf "*" width specifier lets you use a calculated format width, so you can pick the number of zeros to pad with at runtime, making the same code work with any loop length. Assuming there will be N passes through the loop: "filename = sprintf('MyFile%0*d.xml', ceil(log10(N+1)), n)".
Andrew Janke
Should I roll all of these options into my answer (with credits given) or do ya'll want to make your own answers? Because they're getting hidden since there are so many comments here.
Doresoom
@Andrew - Nice - num2str can do the same thing... N=1200; n=55; num2str(n,['%0' num2str(ceil(log10(N+1))),'d']) but both work
Azim
@Doresoom, you can roll my suggestions into your answer :) if you like.
Azim
@Doresoom, feel free to roll mine in too.
Andrew Janke