Lab 5: Practice with for-loops and functions
Practice with for-loops and functions
Task 1a: starline
Write a function called starline
that produces a string of asterisks as specified
by user input. The header of the function will look like this:
function stars = starline(len)
Here are some sample executions of starline
:
>> bar8 = starline(8)
bar8 =
'********'
>> bar4 = starline(4)
bar4 =
'****'
>> singlestar = starline(1)
singlestar =
'*'
>> nostar = starline(0)
nostar =
0x0 empty char array
>>
>> test = starline()
Not enough input arguments.
Error in starline (line 4)
for i=1:nreps
>>
Task 1b: Improved starline
Note in the last example above that starline
generates
an error when no inputs are provided.
Change your starline
function
so that it can handle the case when no inputs are provided.
If no input arguments are provided, starline
returns a string of 10 stars (*) (see examples below).
>> noInputs = starline() noInputs = '**********' >> test = starline(3) test = '***'
Task 1c: markerline
We will continue to make starline
more useful by morphing it into
a function called markerline
(because we won't always be using stars anymore).
Now, the user may, if they choose to, supply the marker to repeat. If the user does
not supply a marker, then the function uses * as the default marker.
The header of the function will look like this:
function line = markerline(nreps, marker)
If no input arguments are provided, markerline
returns a string of 10 stars (*). If only one input argument is provided, then the star (*) marker is used. If two inputs are provided, then the function returns a string of the given length with the given marker.
Here are some sample executions of markerline
using nargin
:
>> noInputs = markerline() noInputs = '**********' >> test = markerline(3) test = '***' >> test = markerline(3,'Y') test = 'YYY' >> test = markerline(5,'$') test = '$$$$$' >> test = markerline(20,'#') test = '####################'