Reputation: 3
I have a function
function [ obsTime, obsWDIR, obsWSPD, obsSWH, obsMWD ] = readObsC(obsFile, endTime)
that when I run it, it gives an output of a huge array ans
, which is the same array as obsTime
. But obsTime
, obsWDIR
, obsWSPD
, etc. don't display. Not a single line of code is supposed to display ans
.
When I'm in debugging mode, I run the code and stop it at the very last line, and it doesn't give an output ans
. Only when I hit 'step' twice and the function ends, does the ans
output appear.
Everything in the function has semicolons.
Why does ans
appear? Where are my other outputs?
Upvotes: 0
Views: 1806
Reputation: 8323
The function declaration specifies the return values, but when you call it, you don't specify anywhere for the output to go. When you call something on the command line, the output is always defaulted to ans
unless you assign a variable to the output of the function when you call it.
I defined a simple function called myfunc
as:
function [one,two,three,four] = myfunc(value1,value2)
Ex, using workspace variables (denoted ws_) to capture function output:
>> [ws_one,ws_two,ws_three,ws_four] = myfunc(1,2)
prints:
ws_one =
1
ws_two =
2
ws_three =
1
ws_four =
2
Upvotes: 1
Reputation: 283634
In your function definition, you name the formal input and output arguments. That determines the name which these arguments will use within the function.
The function has its own environment, and variable names inside the function are completely independent of variable names outside the function, unless you use global
or evalin('caller')
.
You have to provide actual input and output arguments at the time of the call, which determines how the code outside the function refers to those same arguments. There is no automatic passing of arguments simply because the names match! The only automatic thing is that if you don't specify the actual output arguments, the first actual output argument will be ans
and the rest are discarded.
You could have figured this out if you simply read the MATLAB documentation for ans
:
The MATLAB® software creates the ans variable automatically when you specify no output argument.
Upvotes: 1