Menu

Using user-defined functions

Gianluigi Forte

Using user-defined functions

It is possible to define custom functions that can be subsequently used for other computations.
Let make the same example seen in the variable section: we want to compute the area of two squares. The first has a side of 3.14 and the second has a side that is double of the other. But in this case we want to compute also the perimeter of each square and we want to make the same with other three squares with side of 18, 0.12 and 35.62

In this case the fast way is to define two function: square and perimeter.

Note: Square function is present also as built-in function so there is no need to redefine it but we will do it anyway just for educational purpose.

square(x)=x*x
nan

perimeter(x)=4*x
nan

At this point is possible to use the two user-defined functions square and perimeter to compute the required results.

square(3.14)
ans=9.8596

square(3.14*2)
ans=39.4384

square(18)
ans=324

square(0.12)
ans=0.0144

square(35.62)
ans=1268.7844

Note: It is possible to press the up arrow key to show up the previous inserted expression.

Then is possible to use the perimeter function.

perimeter(3.14)
ans=12.56

perimeter(3.14*2)
ans=25.12

perimeter(18)
ans=72

perimeter(0.12)
ans=0.48

perimeter(35.62)
ans=142.48

It is possible also to define function of function like

f=abs(1/x)
nan

g=f(x)*f(x)
nan

g(-13)
ans=0.0059171597633136094675

and multi dimensional functions like

f(x,y,z)=(x+2y)/z
nan

f(3.1,-2,0.01)
ans=310


Related

Wiki: Home

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.