User defined function runs without inputs
1 view (last 30 days)
Show older comments
When running a user-defined function that reads two input arguments, it is possible to overwrite those arguments using the input function, and run by just calling the file name. How is this possible? It is clear that it is not running the file as a function, but why? For example:
function [area] = calcrectarea(l,w) %This function will calculate the area of a rectangle based on user input %of length and width.
%Ask for user input for length and width l=input('Enter the length: '); w=input('Enter the width: ');
%Calculate the area of the rectangle area=l*w;
end
Can be run by simply calling calcrectarea, instead of calcrectarea(l,w) with no error.
0 Comments
Answers (2)
dpb
on 13 Feb 2014
Not unless the function is modified to check the number of inputs and branch around the calls to input and supplies some values internally for them.
But, as written, why are there any arguments, anyway? Matlab does not modify arguments and the function obtains values for the two variables locally but they'll not be passed back to the caller so they're lost (as another poster recently asked a question on semantics of another language which does do so, "Matlab is NOT Fortran" :) ).
If you need the actual values input in the caller you'll need to add them to the list of outputs, not put them in the input argument list (ignoring the abominable alternative of GLOBAL, anyway).
0 Comments
David Young
on 13 Feb 2014
You say "It is clear that it is not running the file as a function" when you give the name without any arguments. I think this points a misunderstanding: the function is being called. That is,
calcrectarea
is the same as
calcrectarea()
and in your case it's also the same as
calcrectarea(l, w)
because the function you have written ignores the values that l and w are given when it is called. Instead, it uses input to get values for l and w. As dpb says, this only affects the values of l and w inside the function.
0 Comments
See Also
Categories
Find more on Fortran with MATLAB 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!