create and name .txt file with fopen

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

采纳的回答

Star Strider
Star Strider 2017-6-22
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 个评论
Jonas K
Jonas K 2017-6-22
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 2017-6-22
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Install Products 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by