User defined function runs without inputs
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
dpb
am 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 Kommentare
David Young
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Fortran with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!