Why am I getting 'ans=45' in this code?
Show older comments
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
More Answers (1)
Guillaume
on 2 Apr 2019
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
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!