Why am I getting 'ans=45' in this code?

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.

 Accepted Answer

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 Comments

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.
Okay is it only for files?
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).

Sign in to comment.

More Answers (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.

Categories

Products

Release

R2018b

Tags

Community Treasure Hunt

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

Start Hunting!