Download presentation
Presentation is loading. Please wait.
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] >> A = [[ 1, 2, 4], [3, 4, 6], [7, 8]] A becomes [1, 2, 4, 3, 4, 6, 7, 8]
3
Cell arrays
4
Cell array – examples
5
Cell – operations
6
Generating 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
7
Idea 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(2:n) Then add a(1) to each of the subsets. Combine the two collections.
9
Since we need to represent a collection of sets, we have two choices: 1. use of cell arrays 2. 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.
10
Example showing how insert works
11
Code for insert function out = insert(i, lst) % inserts i into each membet of lst for j = 1:length(lst) out{j}= [i, lst{j}]; end;
12
Code 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(2:end)); L2 = insert(lst(1), L1); L = [L1, L2]; end;
13
Printing 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 k=1:length(cellset) aprint(cellset{k}); fprintf('\n'); end; function aprint(r) for j = 1:length(r) fprintf('%d', r(j)); fprintf(' '); end; fprintf('\n')
14
Generating 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]
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.