필터 지우기
필터 지우기

create and name .txt file with fopen

조회 수: 124 (최근 30일)
Jonas K
Jonas K 2017년 6월 22일
댓글: Star Strider 2017년 6월 22일
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에서 Low-Level File I/O에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by