Notes for Friday 2/23/07
A simple example where code is repeated: (the first four lines are
repeated)
for ii in 1:8
fprintf('*')
end
fprintf('\n')
fprintf('Kim Druschel\n')
for ii in 1:8
fprintf('*')
end
fprintf('\n')
(what is the outcome?)
We can encapsulate the repeated lines in a function and just call the
function:
function prntlnst
for ii in 1:8
fprintf('*')
end
fprintf('\n')
The above code then becomes
prntlnst
fprintf('Kim Druschel\n')
prntlnst
In the above three lines of code prntlnst invokes the function
prntlnst, and essentially the control of the program goes to the
function, which does what its code says, and then the control goes back
to the next line of code. When one sees the line of code prntlnst in
aprogram taht is called a "call" to the function prntlnst. As long as
one knows what prntlnst does, it is much each to quickly read
what the above three lines of code accomplish. Further, one can break
the code into pieces and work on the individual pieces or functions.
We could make the above function more useful by introducing parameters
to 1) effect the length of the for loop (and consequently the line that
is printed) and 2) what is repeatedly printed across the line.
Parameters are akin to arguments for a mathematical function and so the
syntax is similar.
% Function to print n b's across a line and then go down one line.
%Parameters are n and b-n is an integer, b is a letter or string
function prntln(n,b)
for ii in 1:n
fprintf(b)
end
fprintf('\n')
Now for a liitle program to call this function.
prntln(5,'he')
prntln(30,'ko')
k=40;
m='bee'
prntln(k,m)
prntln(k-8,m)
What is output by this?
Note that on each call to the function prntln there are two values
replacing the parameters. If the number and type of parameters did not
match we would get an error. Also it perfectly acceptable to have a
variable or expression in the place for a parameter, as we do with the
last four lines of code.
As with mathematical functions, the functions we write with MATLAB can
return values:
function u = f(m)
u=m*m+m^3;
Calls to this include:
p=f(3) % this will set p to 36 (9+27)
c=f(1)+f(2) % this will set c to 13
fprintf('%f', f(1.1)) % will print whatever 1.1*1.1 +1.1^3 is.
Most everything we've written so far can be put into a function. For
example we could write two functions for computing the volume and
surface area of a silo;
function v=silovol(r,h)
v= 2/3 * pi * r ^3+ pi*r^2*h;
function sa=silosa(r,h)
sa= 2 * pi * r ^2+ 2*pi*r*h;
And here is a small program which uses these functions:
ans='y'
while (ans == 'y')
x=input('enter the radius of the silo')
u=input('enter the height of the silo')
fprintf('The volume of that silo is %f\n', silovol(x,u))
fprintf('The surface area of that silo is %f\n', silosa(x,u))
ans=input('Do you want to repeat for other silos? y or n with
quotes around them')
end