Clear Filters
Clear Filters

create and name .txt file with fopen

123 views (last 30 days)
Hello, I have the following piece of code:
num_lights = 3;
light_direction = [1, 2, 3; 4, 5, 6; 7, 8, 9];
fileID = fopen('test_name.txt','w');
fprintf(fileID, '%i \n', num_lights);
fprintf(fileID, '%f %f %f \n', light_direction);
fclose(fileID);
The problem is, I don't want a fixed name for my file. It should look somewhat like this:
fileID = fopen('test_name', xyz, '.txt','w');
xyz would be a %s.tring that is defined earlier. What is my mistake. The documentation for fopen doesn't seem to include more complex names. And I don't want to use a rename function since this wouldn't be proper programming (I was told...)
Thanks for your help! J

Accepted Answer

Star Strider
Star Strider on 22 Jun 2017
Assuming ‘xyz’ is a string, this should do what you want:
xyz = ...; % Define ‘xyz’
fileID = fopen(sprintf('test_name%s.txt', xyz) ,'w');
If it is numeric, then replace ‘%s’ with ‘%d’ or whatever format descriptor is most appropriate.
  2 Comments
Jonas K
Jonas K on 22 Jun 2017
thanks! everythings works!
just had to figure out that xyz = 'string' needed to be in apothropies. one might think i have no idea what i'm doing:D
Star Strider
Star Strider on 22 Jun 2017
My pleasure!
Strings are actually character arrays, and are designated with single quotes. The quotes themselves are not actually parts of the character array, they just designate it as such. (To make strings even more complicated, there is now a string (link) variable type that first appeared in R2016b. I mention that because ‘string’ is now a function so using it as a variable name will ‘overshadow’ the function, making the function unusable.)
No worries — none of us were born knowing any of this. Some of us just have a bit more experience with it by now.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!