Writing A Function: Why Functions Are Better Than Scripts
Writing A Function: Why Functions Are Better Than Scripts
Writing a function
function showarea = trianglearea(base,height)
to calculate the area of a triangle
OR
Writing a script
base = 1; # hardcoded user input prior to runtime
(m file) called trianglearea.m
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)