Вы находитесь на странице: 1из 67

Introduction to Matlab

& Data Analysis

Lecture 7:
Recursion + Structures, cells and files

Eran Eden, Weizmann 2008

Recursion
2

Recursion

Recursion

What is a recursion?
A recursive definition is when something is defined in
terms of itself

So how does it ever stop?


Recursion can also be defined in terms of a simpler version

of itself

Why are we learning recursion?


4

Recursion
function babushka()
babushka();
disp('B');
>> babushka
How many times will the function print the letter B?
function babushka()
babushka();
function babushka()
disp('B');
babushka();
function babushka()
disp('B');
babushka();
disp('B');

Recursion

None, the function babushka never gets


to print the letter B.

Recursion
function babushka()
disp('B');
babushka();
>> babushka
How many times will the function print the letter B?
function babushka()
disp('B');
babushka();

function babushka()
disp('B');
babushka();

function babushka()
disp('B');
babushka();

Recursion
function babushka(i)
if i < 1
return ;
end
babushka(i - 1);
disp(i);

A stopping condition

A recursive call with a simplified


version of the original call

>> babushka(3)

What will the function print?

Recursion
function babushka(i)
3
if i < 1
return ;
end
babushka(i - 1);
function babushka(i)
disp(i);
if i < 1

return ;
end
babushka(i - 1);
disp(i);

The 0 box got hit by return


so it will not print 0, but the
other boxes are fine and
will exit with the disp
command

function babushka(i)
1
if i < 1
return ;
end
babushka(i - 1);
function babushka(i)
disp(i);
if i < 1

return ;
end
babushka(i - 1);
disp(i);
9

Recursion
function babushka(i)
if i < 1
return ;
end
disp(i);
babushka(i - 1);

>> babushka(3)

What will the function print?

10

Factorial

Design a recursion program that computes the


factorial of a number n

n! = n * (n 1) * (n 2) * 1

Hint: To solve a problem using a recursion we need


two things:

A recursive formulation: n = n * (n - 1)!


A stopping condition (e.g. a situation where the problem is
that simple that we don't really need to solve it recursively)
if n <= 1 n! = 1

11

Factorial
function

n_fac = facto (n)

if n <= 1
n_fac = 1;
return;
end
n_fac = n * facto (n - 1);

A stopping condition

A recursive call with a simplified


version of the original call

12

Our old friend Fibonacci


"A certain man put a pair of rabbits in a place surrounded on all sides by a wall. How many pairs of rabbits
can be produced from that pair in a year if it is supposed that every month each pair begets a new pair which
from the second month on becomes productive? " - Liber abaci, Fibonacci

n=0

n=1

n=2

n=3

n=5

13

Solving Fibonacci with loops


(reminder)
index = input('Please enter a Fibonaci series index number');

if index < 0
vec = [];
elseif index == 1
vec = [1];
else
vec = [1 1]; prev = 1; curr = 1;
for i = 2 : index
next = curr + prev;
prev = curr;
curr = next;
vec = [vec, next];
end
end
disp(vec);

14

Fibonacci

Solving the Fibonacci problem using recursion is


more compact and simple
function num = fib(index)
if index <= 1
num = 1;
return;
end

A stopping condition

num = fib(index - 1) + fib(index - 2);


A recursive call with a simplified
version of the original call
15

Fib(n)

What does fib(3) do?


num=fib(2)+fib(1)
What is fib(2)?
num=fib(1)+fib(0)
What are fib(1) and fib(0)?
By definition: num=1 for both.
So fib(2) returns the value num:
fib(2)=fib(1)+fib(0)=1+1 etc.

Conclusion: Some problems are more


naturally solved using a recursion
function num = fib(index)

if index < 0
vec = [];
elseif index == 1
vec = [1];
else
vec = [1 1];
prev = 1;
curr = 1;

function num = fib(index)


if index <= 1
num = 1;
return;
end
num = fib(index - 1) + fib(index - 2);

for i = 2 : index
next = curr + prev;
prev = curr;
curr = next;
vec = [vec, next];
end
end
disp(vec);
17

La-cucaracha

Johny the spider loves to climb stairs.


He can jump either 1 or 2 steps at a time.

How many paths can he choose from when climbing 10 stairs?

Think of a simple, and short function to solve this problem.


18

La-cucaracha
K

possibilities

Total_num

1,1
2

1,1,1
2,1

1,2
4

1,1,1,1
2,1,1
1,2,1
1,1,2
2,2

19

Cell arrays & Structures

20

What are cells and structures?

So far we could only save arrays and matrices


that contain elements of the same type
(numbers, characters ,etc.)

x = [ 1,
4,
y = [shusha]

5,

2,

-1]

21

What are cells and structures?

Sometimes we want to store elements of different


types within the same container
Cells and structures enable us to do just that!

Why do we actually need this?

22

Cells versus structures

Cells use addresses


1

Structures use names


picaso

rembrant

van-gogh

leonardo

michael

23

Cell array creation

One way to create a cell (cell indexing):

>> x(1,
>> x(1,
>> x(2,
>> x(2,
>> x
x =

1)
2)
1)
2)

=
=
=
=

{
{
{
{

[1 2 3; 4 5 6; 7 8 9] };
2.5 };
'bababluba' };
[10 : -2 : 0] };

[3x3 double]
'bababluba'

Note that Matlab shows


that x is a 2*2 array but
does not show the
content of all cells

[
2.5000]
[1x6 double]

Alternatively the following statement creates the same cell array


(content addressing)

x{1,
x{1,
x{2,
x{2,

1}
2}
1}
2}

=
=
=
=

[1 2 3; 4 5 6; 7 8 9] ;
2.5 ;
'bababluba' ;
[10 : -2 : 0] ;

24

Cell array creation

The two commands:

x(i, j) = { y }
and
x{i, j} = ( y )
have the same outcome.
Both store the content of the variable y inside the (i, j) element of cell
array x.

25

Cell array creation

If you assign a cell to an existing variable that is not


a cell Matlab will report an error!

Example:
>> x = 1;
>> x(1, 1) = {1 : 4}
??? Subscripted assignment dimension mismatch.

How can you correct this ?


>> clear x

26

Cell array manipulation

Cell array manipulation is a natural extension to the


standard array manipulation we have used so far
Example #1:

x =
[3x3 double]
'bababluba'

[
2.5000]
[1x6 double]

[4x4 double]
'shusha'

[
4]
[1x4 double]

y =

>>z = [x; y]
[3x3 double]
'bababluba'
[4x4 double]
'shusha'

[
[1x6
[
[1x4

2.5000]
double]
4]
double]

27

Cell array manipulation


>>a = z([1, 3], :)
[3x3 double]
[
[4x4 double]
[

2.5000]
4]

>>size(a)
ans =

28

Retrieving cell array content

There are two different ways to retrieve the content


of a cell array x :

( ) identify the cells without looking at their content (cell


indexing)
Example: x(1,2)
{ } access the content of the cells (content addressing)
Example: x{1,2}

29

Retrieving cell array content


Retrieving the content of a cell array
using cell indexing () and
content indexing {}
is same same BUT different

30

Retrieving cell array content


>>
>>
>>
>>

x(1,
x(1,
x(2,
x(2,

How can we retrieve the content of a cell within a cell array?

1)
2)
1)
2)

=
=
=
=

{
{
{
{

[1 2 3; 4 5 6; 7 8 9] };
'bababluba' };
[1 : 10] };
'A' };

Option #1: apply content addressing

>> b = x{1, 1}
b =
1
2
4
5
7
8

>> c = x{1, 2}
c =
bababluba

3
6
9

>> class(b)
double

>> class(c)
char
31

Retrieving cell array content


>>
>>
>>
>>

x(1,
x(1,
x(2,
x(2,

How can we retrieve the content of a cell within a cell array?

1)
2)
1)
2)

=
=
=
=

{
{
{
{

[1 2 3; 4 5 6; 7 8 9] };
'bababluba' };
[1 : 10] };
'A' };

Option #2: apply cell indexing

>> b = x(1, 1)
b =
[3x3 double]
>> c = x(1, 2)
c =
'bababluba'

>> class(b)
cell

>> class(c)
cell
32

Cell arrays of strings

One of the most important usages of cells is


to store and manipulate strings of different
sizes in one array.

This will be taught in the tutorial

33

Structures

34

Structures creation
Structure name

Structure field

>> dogs.name
>> dogs.breed
>> dogs.age
>> dogs.special_food
>> dogs
dogs =

name:
breed:
age:
special_food:

= 'rufus';
= 'Bulldog';
= 1.5;
% in years
= 'none';

'rufus'
'Bulldog '
1.5000
'none'

35

Array of structures

Adding more dogs

>>
>>
>>
>>

dogs(2).name
dogs(2).breed
dogs(2).age
dogs(2).special_food

=
=
=
=

'kin-kong';
'Chihuahua';
5;
'filet mignon';

>>
>>
>>
>>

dogs(3).name
dogs(3).breed
dogs(3).age
dogs(3).special_food

=
=
=
=

'wong';
'pekingese';
20;
'sushi';

>> dogs =
1x3 struct array with fields:
name
breed
age
special_food

36

Retrieving structure content

Retrieving a specific dog

>> x = dogs(2)

x =
name:
breed:
age:
special_food:

'kin-kong'
'Chihuahua'
5
'filet mignon'

37

Retrieving structure content

Retrieving information on a specific dog

>> x.breed
ans =
Chihuahua
>> dogs(2).breed
ans =
Chihuahua
38

Retrieving structure content


(comma separated lists)

We can simultaneously retrieve a field from several dogs

>> dogs.age
ans =
1.5000
ans =
5
ans =
20

>> ages = dogs.age


??? Illegal right hand side in assignment. Too many elements.

We can solve this by


converting the list to an
array of numbers

>> ages = [dogs.age]


ages =
1.5000

5.0000

20.0000

39

Retrieving structure content


(comma separated lists)

We can simultaneously retrieve a field from several dogs

>> dogs.name
ans = rufus
ans = kin-kong
ans = Wong
>> names = dogs.name
??? Illegal right hand side in assignment. Too many elements.

Converting the list to an


array creates another
problem

>> names = [dogs.name]


names =
rufuskin-kongwong
>> names = {dogs.name}
names =
'rufus'
'kin-kong'

'wong'

A better solution is to
convert the list into a
cell array of strings 40

Structure and cell arrays summary example

We are going to build a program for managing a five star hotel for
dogs
The program will manage the hotel log and enable:

check-in of a new dog


check-out of a dog (according to dog name)
generation of a report of the hotel occupancy
Automatically calculate the bill

41

Structure and cell summary example

We start with a TOP down design as discussed in previous lecture

42

Structure and cell summary example


function dogs = dogHotel ()
< Welcome message and structure init>
while(1)
<ask the user for check in or check out option>
if <check-in option >
< checkIn >
elseif < check-out option >
< check-out >
< report bill >
end
<print Inventory>;
end
43

Structure and cell summary example


function dogs = dogHotel ()
disp('Generating a structure for storing dog hotel information');
dogs = [];
while(1)
choice = input('*** Press I for dog check-In, O for dog Check-Out and Q to quit: ', 's');
if choice == 'I'
dogs = checkIn(dogs);
elseif choice == 'O'
dog_name = input('Enter the name of the dog you wish to check-out: ', 's');
[dogs, bill] = checkOut(dogs, dog_name);
disp(['The bill is', num2str(bill), '$']);
elseif choice == 'Q'
return;
end
printInventory(dogs);
end

44

Structure and cell summary example


function dogs = checkIn(dogs)
n_dogs = size(dogs, 2);% the second dimension is the number of cols, in our case the
%number of dogs
dogs(n_dogs
dogs(n_dogs
dogs(n_dogs
dogs(n_dogs
dogs(n_dogs
stay at the
dogs(n_dogs

+ 1).name
= input('Enter dog name: ', 's');
+ 1).breed
= input('Enter dog breed: ', 's');
+ 1).age
= input('Enter dog age: ');
+ 1).special_food = input('Enter dog special food: ', 's');
+ 1).days_in_hotel = input('Enter number of days dog will ...
hotel: ');
+ 1).owner_mobile = input('Enter mobile phone of dog owner: ', 's');

45

Structure and cell summary example


function [dogs, bill] = checkOut(dogs, dog_name)
names
index
bill

= {dogs.name};
= find(strcmp(names, dog_name));
= 0;

if isempty(index)
message = ['There is no dog in our hotel named ', dog_name];
disp(message);
return;
end
%Computing the bill
d = dogs(index);
bill = 100 * d.days_in_hotel;

%100$ per day

if strcmp(d.breed, 'pitbull')
bill = bill * 1.2;
end
if ~strcmp(d.breed, 'None')
bill = bill * 2;
end
%Erasing the dog
dogs(index) = [];

%erasing the dog

46

Structure and cell summary example


function printInventory(dogs)
disp('The following dogs are currently staying in the hotel: ')
for i_dog = 1 : size(dogs, 2)
disp(dogs(i_dog).name);
end

47

Running example
>> dogs = dogHotel
Generating a structure for storing dog hotel information
*** Press I for dog check-In, O for dog Check-Out and Q to quit: I
Enter dog name: rufus
Enter dog breed: bulldog
Enter dog age: 1.5
Enter dog special food: None
Enter number of days dog will stay at the hotel: 10
Enter mobile phone of dog owner: 054-777777777
The following dogs are currently staying in the hotel:
Rufus
*** Press I for dog check-In, O for dog Check-Out and Q to quit: I
Enter dog name: king-kong
Enter dog breed: Chihuahua
Enter dog age: 5
Enter dog special food: filet mignon
Enter number of days dog will stay at the hotel: 20
Enter mobile phone of dog owner: 050-88882222
The following dogs are currently staying in the hotel:
rufus
king-kong

48

Running example
*** Press I for dog check-In, O for dog Check-Out and Q to quit: I
Enter dog name: wong
Enter dog breed: pekingese
Enter dog age: 20
Enter dog special food: sushi
Enter number of days dog will stay at the hotel: 1000
Enter mobile phone of dog owner: 050-00000001
The following dogs are currently staying in the hotel:
rufus
king-kong
Wong
*** Press I for dog check-In, O for dog Check-Out and Q to quit: O
Enter the name of the dog you wish to check-out: Lassie
There is no dog in our hotel named Lassie
The bill is 0$
The following dogs are currently staying in the hotel:
rufus
king-kong
Wong

49

Running example
*** Press I for dog check-In, O for dog Check-Out and Q to quit: O
Enter the name of the dog you wish to check-out: king-kong
The bill is 4000$
The following dogs are currently staying in the hotel:
rufus
Wong
*** Press I for dog check-In, O for dog Check-Out and Q to quit: Q

50

Final words on cells and structures


One could have written the dog hotel program without structures.
However, using structures and cells to aggregate variables that
belong to the same entity makes the program easier to design, easier
to debug and more readable.

Additionally, many of the Matlab built in toolboxes, use


structures we will see in the coming lectures
51

Reading and writing to files

We often want to read files and store them in


variables

We often want to write the results into a file

Examples

Examples

Matlab has several mechanisms to read and


write to files...
52

Reading and writing to files

First well see Low level I/O


Suppose we want to read the content of the file
the_road_not_taken.txt and copy it to another file
the_road_not_taken_edited.txt . At the beginning
of each line we want to add the line number.
The road not taken.txt

53

Reading and writing to files


The Road Not Taken
TWO roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear;
Though as for that, the passing there
Had worn them really about the same,

And both that morning equally lay


In leaves no step had trodden black.
Oh, I marked the first for another day!
Yet knowing how way leads on to way
I doubted if I should ever come back.
I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference.

54

Reading and writing to files

4 general steps for copying one file into another:


1) Open the source file & open a target file
fid = fopen(<file name>, <permission>)
% opens the file <file name> for read access
2) Read the lines, one by one and store in a variable
line = fgetl(fid)
% returns the next line of a file associated with file identifier fid as a MATLAB string
and discards newline characters
3) Write the lines into the target file
fprintf(fid, format, variables);
% Write formatted data to file specified by fid
4) Close the source and the target files
fclose(fid)
% closes the file associated with file identifier fid

55

Reading and writing to files


function addLineCount(f_name_in, f_name_out)
%opening the source file
fid_in = fopen(f_name_in, 'r');
if (fid_in == -1)
disp('Unable to open source file !');
return;
end

Read permission

Write permission
%opening target file
fid_out = fopen(f_name_out, 'w');
if (fid_out == -1)
disp('Unable to open target file !');
return;
end
(Continued in the next slide)

56

Reading and writing to files


(Continued from previous slide)
i_line = 1;
while 1
line = fgetl(fid_in);
if ~ischar(line)
break;
end
fprintf(fid_out, '%g %s\n', i_line, line);
i_line = i_line + 1;
end
fclose(fid_in);
fclose(fid_out);

At the end of a file theres a


special End Of File character
whose value is -1.

What is fprintf?
Write data to text
file
Dont forget to close the files after
your done with them
57

Reading and writing to files


>> f_name_in = 'C:\Matlab and Data Analysis\scripts\Lecture 7\The road not taken.txt
>> f_name_out = 'C:\Matlab and Data Analysis\scripts\Lecture 7\The road not taken edited.txt
>> addLineCount(f_name_in, f_name_out);
The Road Not Taken
TWO roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear;
Though as for that, the passing there
Had worn them really about the same,
And both that morning equally lay
In leaves no step had trodden black.
Oh, I marked the first for another day!
Yet knowing how way leads on to way
I doubted if I should ever come back.
I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

The Road Not Taken


TWO roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear;
Though as for that, the passing there
Had worn them really about the same,
And both that morning equally lay
In leaves no step had trodden black.
Oh, I marked the first for another day!
Yet knowing how way leads on to way
I doubted if I should ever come back.
I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference.

58

Reading and writing to files

Suppose we want to write the poem backwards so that the last


line will appear first and so on. We want to overwrite the source
file.

The road not taken.txt

59

Reading and writing to files


function reversePoem(f_name)
Read and write

%opening the source file


permission
fid = fopen(f_name, 'r+');
if (fid == -1)
disp('Unable to open source file !');
return;
end

(Continued in the next slide)


60

Reading and writing to files


%Reading the file and storing in poem cell array
i_line = 1;
while 1
line = fgetl(fid);
poem{i_line} = line;
if ~ischar(line)
break;
end
i_line = i_line + 1;

Rewinds fid to point to the


beginning of the file.
Otherwise, text append at
the end.

end
frewind(fid);
%Overwriting original file and writing poem backwards
for i_line = length(poem) : -1 : 1
poem(i_line) or
fprintf(fid, %s\n',
);
poem{i_line} ?
end
fclose(fid);

61

Reading and writing to files


>> reversePoem('C:\Matlab and Data Analysis\scripts\Lecture 7\The road not taken.txt)
The Road Not Taken
TWO roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear;
Though as for that, the passing there
Had worn them really about the same,
And both that morning equally lay
In leaves no step had trodden black.
Oh, I marked the first for another day!
Yet knowing how way leads on to way
I doubted if I should ever come back.
I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference.

And that has made all the difference.


I took the one less traveled by,
Two roads diverged in a wood, and I,
Somewhere ages and ages hence:
I shall be telling this with a sigh

I doubted if I should ever come back.


Yet knowing how way leads on to way
Oh, I marked the first for another day!
In leaves no step had trodden black.
And both that morning equally lay
Had worn them really about the same,
Though as for that, the passing there
Because it was grassy and wanted wear;
And having perhaps the better claim
Then took the other, as just as fair,
To where it bent in the undergrowth;
And looked down one as far as I could
And be one traveler, long I stood
And sorry I could not travel both
TWO roads diverged in a yellow wood,
The Road Not Taken

62

Reading and writing to files

Matlab has high level I\O functions for reading data.

Advantages: it is easier and requires less programming than


low level functions.
Limitations: it will only work if the data is in a predefined
format.

63

Reading and writing to files

Example: we have a text file called data_table.txt that looks as follows:

Name

Badal
Badri
Badrinath
Bahubali
Bahuleya
Bajrang
Balaaditya
Balachan
Balagovind
Balaji
Balakrishna
Balamani
.

Age
77
100
22
95
33
48
78
78
64
16
30
89

Weight Salary
79
86
79
91
77
85
106
86
120
112
76
79

5909
5290
6960
6233
8314
5870
9144
7055
7570
5021
9066
6253

64

Reading and writing to files

The importdata command

>> file = importdata('C:\Matlab and Data Analysis\table_data.txt')


file =

All the numeric data is


stored in a double array
called data

data: [93x3 double]


textdata: {94x4 cell}
>> file.data
ans =
25
38
83
99
27
92
42
2
38
99
22

85
76
86
116
67
78
113
117
79
60
100

9056
8621
5115
7510
5433
9053
6853
8798
6703
9746
7875 ...

All the char data is


stored in a cell array
called textdata

65

Reading and writing to files


>> file.textdata
ans =
'Name'
'Badal'
'Badri'
'Badrinath'
'Bahubali'
'Bahuleya'
'Bajrang'
'Balaaditya'
'Balachandra'
'Balagovind'
'Balaji'
'Balakrishna'
'Balamani'
...

'Age'
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]

'Weight '
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]

'Salary '
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]

66

Reading and writing to files

There are many other functions for reading and


writing to files.

For example reading the content of an Excel spreadsheet


can easily be done with the function xlsread.

Some of these functions will be discussed in the


tutorial
For more details just use help
67

Вам также может понравиться