Functions: ans at end...where it is coming from?

5 次查看(过去 30 天)
In entering the following function:
function [ft,in] = MetricToImperial(m)
% Input: m = measurement in metres
% Outputs: ft = number of feet
% in = number of inches
m = 2;
% Calculate the total number of cms
cm = m * 100;
% Calculate the total number of inches
totalInches = cm/2.54;
% Calculate the total number of feet, ignoring the value after decimal
ft = floor(totalInches/12)
% Find the remaining number of inches
in = totalInches - 12*ft
return
When running the function matlab returns:
EDU>> MetricToImperial
ft =
6
in =
6.7402
ans =
6
Now i was wondering why I get the ans = 6 at the end. All i want is the ft and in answer. I have tested it as a script and it works that way so I know it must be something to do with my inputs and outputs.
I have also noticed if I leave line 1 as
function [] = MetricToImperial(m)
it gives me the result I want - so something is wrong as I'm saying there's no output variables but there is.
Is this the correct way to create a function? I am very new to this so any help is appreciated.

采纳的回答

kjetil87
kjetil87 2013-7-28
It is because you are typing:
>> MetricToImperial
and nothing more. Since your are not assigning MetricToImperial output to anything, and neither supressing the function in the matlab command line, the first output "in" will be returned as
ans
where ans in this case is the answer from your function.
Try this if it is not yet clear:
>> [out1,out2]=MetricToImperial
>> [out1,out2]=MetricToImperial;
>> MetricToImperial;
>> out1=MetricToImperial
The frist will return
out1=
6
out2=
6.7402
while number two will write nothing in the command window but it will assign the outputs out1 and out2.
etc
So the ans=6 is not random at all, it is the returned value from your function.

更多回答(1 个)

Honglei Chen
Honglei Chen 2013-7-27
The first two answer you get is due to the fact you didn't end the corresponding lines in your function with semi-colon. The ans is populated because your function has an output but the output is not specified when you invoke the function. You should add semi-colon behind both lines and invoke the function as
[ft,in] = MetricToImperial
Finally your input, m, does not seem to be used at all.
  3 个评论
Walter Roberson
Walter Roberson 2013-7-27
You might intend it as your input, but you are assigning it in the function, making it useless to pass it as your input. You probably should not be assigning it in your function.
Anna
Anna 2013-7-27
Upon your comment I have realized what you meant so line 1 to reads:
function [ft,in] = MetricToImperial(m)
and when calling the function I still get that random ans = 6. I have put semi-colons after every line.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by