Title: Lec 13 Oct 17
1- Lec 13
Oct 17 - cell arrays
- structures
- advanced recursive programs
2- Cell arrays
- suppose we want to represent a collection of
sets such as - 1, 2, 4, 3, 4, 6, 7, 8
- Each set can be represented by vector
-
- 1, 2, 4, 3, 4, 6, 7, 8
- gtgt A 1, 2, 4, 3, 4, 6, 7, 8
- A becomes 1, 2, 4, 3, 4, 6, 7, 8
3Cell arrays
4Cell array examples
5Cell operations
6Generating all subsets of a given set Given a
set, like 1, 3, 4, the subsets are
1 3 4 1 3 1
4 3 4 1 3 4 We want to write a program to
generate all the subsets of a given collection
7Idea behind algorithm recursion This is a
problem for which non-recursive solutions are
significantly harder than recursive
solutions. Idea input array is a of length
n. Recursively find all subsets of a(2n) Then
add a(1) to each of the subsets. Combine the two
collections.
8(No Transcript)
9- Since we need to represent a collection of sets,
we have two choices - use of cell arrays
- use of two-dimensional arrays
- The latter is not suitable for this problem since
the sizes of the subsets are not the same - We need a function insert that inserts a given
number into all the sets of a given collection.
10Example showing how insert works
11Code for insert
function out insert(i, lst) inserts i into
each membet of lst for j 1length(lst)
outj i, lstj end
12Code for subsets function L subsets(lst)
generates all subsets of lst if length(lst) 0
L elseif length(lst) 1 L
lst(1), else L1 subsets(lst(2end))
L2 insert(lst(1), L1) L L1,
L2 end
13Printing the contents of a cell array function
setprint(cellset) prints every member of the
cell in one line assume cellset is a collection
of sets of integers for k1length(cellset)
aprint(cellsetk) fprintf('\n') end function
aprint(r) for j 1length(r) fprintf('d',
r(j)) fprintf(' ') end fprintf('\n')
14Generating all permutations of a given
set Example set 1 3 4 Permutations 1 3
4 1 4 3 3 1 4 3 4 1 4 1 3 4 3 1