I am trying to make a file named text.txt and write numbers 1 to 5 in it, and then print them.
x = [1 2 3 4 5]
a = fopen('test.txt','w');
fprintf(a,'%f\n',x)
fclose(a);
The output I'm getting is:
x =
1 2 3 4 5
ans =
45
Why am I getting ans = 45 ? Neither have I used a variable named ans, nor defined any function in it.

 채택된 답변

Image Analyst
Image Analyst 2019년 4월 2일

1 개 추천

fprintf() reports the number of bytes written. If you don't end that line with a semicolon, it will get reported to the command window. Use a semicolon at the end of the line to suppress that if you don't want it.

댓글 수: 3

Shaona Bose
Shaona Bose 2019년 4월 2일
I followed your suggestion and ans did not appear again, but I removed the semi-colon after fprintf in another program and no byte count was output.
Shaona Bose
Shaona Bose 2019년 4월 2일
Okay is it only for files?
Image Analyst
Image Analyst 2019년 4월 3일
Yes. If you put 1 or leave out the file handle, it prints the stuff to the command window but does not also report the number of characters it printed (that would be annoying and unnecessary).

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2019년 4월 2일

1 개 추천

If a function normally return an output but you don't assign this output to a variable, matlab automatically create a variable called ans to receive that output.
For example, if at the command window you do:
x = 6;
x+2; %output not assigned to anything
You'll now see in the variable browser an ans variable with a value of 8, the result of x+2.
Separately, if you don't terminate a function call with a semi-colon, matlab will display the output in the command window:
>>x+2
ans =
8
You're calling fopen without a semi-colon, and not assigning the output to any variable, so matlab is showing you its output, assigned to ans. The 45 is the number of characters written by fopen.
Terminate the fopen call with a ; and you won't see that ans anymore.

카테고리

제품

릴리스

R2018b

태그

질문:

2019년 4월 2일

댓글:

2019년 4월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by