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.
采纳的回答
更多回答(1 个)
Guillaume
2019-4-2
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!