Why Functions are better than scripts
Writing a function
function showarea = trianglearea(base,height)
to calculate the area of a triangle
Commented [PP1]: function showarea =
showarea = 0.5*(base.*height); trianglearea(base,height)
end Here the keyword is function, showarea is the output
variable and base and height are the input variables
Calling the function from the command line and the formula showarea= 0.5*(base.*height) is the
Showarea1 = trianglearea(1,5) #function callin which we pass user input during runtime transfer function which transforms the input into an
output which gets returned as part of the function called
Showarea1 = trianglearea that calculates the area of the triangle
2.5000
Showarea2 = trianglearea(2,5) #function callin which we pass user input during runtime
Showarea2 =
5.0000
OR
Writing a script
base = 1; # hardcoded user input prior to runtime
(m file) called trianglearea.m
height = 5; # hardcoded user input prior to runtime
a = 0.5*(base.*height)
Calling the script from the command window
triangle area #script call in the command line
a =
2.5000
Note: functions are more powerful that scripts because in the script we hardcode variables prior to runtime so
there is no repeatability in reusing the program over and over again. We can see that in the code above that
during runtime we were able to pass (1,5) and (2,5) so we reused the function 2x and that is why functions are
more repeatable because they allow us to pass parameters (base, height) during runtime and give a consistent
output whereas the output for the script is prone to human error as the output of 2.500 depends on the
hardcoded variable values base =1 & height =5 so its not repeatable because in order to get 5.000 we have to
manually change the hardcoded variable values from base =1 and height =5 to base = 2 and height = 5 which is
tedious. For functions it was a simple as writing Showarea2 = trianglearea(2,5) to accurately get
the output for another set of input parameters that were different from (1,5)