Beruflich Dokumente
Kultur Dokumente
Oct 15
Recursion more examples
Chapter 8 problems and solutions
Cell arrays, Chapter 10
Recursive functions
Before we conclude this chapter, we will discuss
recursive functions, those that can call themselves.
We have examples of functions that call other
functions, e.g. insertionsort calling insert etc.
If f(n) is defined in terms of f(n 1), as for example,
in the case of factorial, why not let f call itself?
n! = n x (n 1)!
Or in matlab:
fact(n) = n .* fact(n 1)
12 2 3 4 4 5
merge(A, 2, 2, B, 9,10) should return the array 1 2 4
merge(A, 3, 4, B, 9, 8) should return 5 7 since the
second array is empty. (high index < low index means
the array is empty.)
Merge function
function out = merge(A, B)
if length(A)==0
out = B;
elseif length(B) == 0
out = A;
else
if A(1) <= B(1)
temp =A(1);
out = [temp, merge(A(2:end),B)];
else
temp = B(1);
out = [temp, merge(A,B(2:end))];
end;
end;
Merge-sorting
To sort an array, recursively sort the two halves, then
apply merge.
function out=mergesort(A)
if length(A)==1
out = A;
else
s = length(A);
mid = floor(s/2);
out1 = mergesort(A(1:mid));
out2 =
mergesort(A(mid+1:end));
out = merge(out1, out2);
end
Exercise 8.1.
>> repeat([2 3; 3 1; 4 2]
ans =
[222344]
Exercise 8.1.
>> repeat([2 3; 3 1; 4 2]
ans =
[222344]
Exercise 8.8
Write a function intoBits to take an integer number
as input and output a string of 0s and 1s
representing the number in base 2.
Exercise 8.11
Write functions minAll, minCol and minRow that find
the overall minimum, column minima and row
minima of a matrix A.
Exercise 8.11
Write functions minAll, minCol and minRow that find
the overall minimum, column minima and row
minima of a matrix A.
min(min(matrix)) %Minimum element of the whole matrix
min(matrix); %Minimum element of each column
min(transpose(matrix)); %Minimum element of each row
Lec 13
Oct