32
Previous Lecture: Characters and strings Today’s Lecture: More on chars and strings Introduction to cell arrays File input/output Using built-in function sort Announcement: Project 4 due tonight at 11pm

Previous Lecture: Today’s Lecture

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Previous Lecture: Today’s Lecture

Previous Lecture: Characters and strings

Today’s Lecture: More on chars and strings Introduction to cell arrays File input/output Using built-in function sort

Announcement: Project 4 due tonight at 11pm

Page 2: Previous Lecture: Today’s Lecture

Lecture 18 6

Example: censoring words

function D = censor(str, A)% Replace all occurrences of string str in % character matrix A with X’s, regardless of % case.% Assume str is never split across two lines.% D is A with X’s replacing str.

AU s M A T L A Bei n t h a t l a b .

U s M A T X X Xei n t h a t X X X .

D

Function strcmpidoes case-insensitive string comparison

Page 3: Previous Lecture: Today’s Lecture

Lecture 17 7

function D = censor(str, A)% Replace all occurrences of string str in character matrix A, % regardless of case, with X's.% A is a matrix of characters. % str is a string. Assume that str is never split across two lines.% D is A with X's replacing the censored string str.

D= A;ns= length(str);[nr,nc]= size(A);

% Build a string of X's of the right length

% Traverse the matrix to censor string str

Page 4: Previous Lecture: Today’s Lecture

Lecture 17 8

function D = censor(str, A)% Replace all occurrences of string str in character matrix A, % regardless of case, with X's.% A is a matrix of characters. % str is a string. Assume that str is never split across two lines.% D is A with X's replacing the censored string str.

D= A;ns= length(str);[nr,nc]= size(A);

% Build a string of X's of the right lengthXs= char( zeros(1,ns));for k= 1:ns

Xs(k)= 'X';end

% Traverse the matrix to censor string strfor r= 1:nr

for c= 1:nc-ns+1if strcmpi( str , A(r, c:c+ns-1) )==1

D(r, c:c+ns-1)= Xs;end

endend

Returns an array of type doubleChanges the type to char

AU s M A T L A Be

i n t h a t l a b .

X XXXs

1

X XX2 3 10

Case insensitive comparison of strings

Page 5: Previous Lecture: Today’s Lecture

Lecture 17 9

function D = censor(str, A)% Replace all occurrences of string str in character matrix A, % regardless of case, with X's.% A is a matrix of characters. % str is a string. Assume that str is never split across two lines.% D is A with X's replacing the censored string str.

D= A;ns= length(str);[nr,nc]= size(A);

% Build a string of X's of the right lengthXs= char( zeros(1,ns));for k= 1:ns

Xs(k)= 'X';end

% Traverse the matrix to censor string strfor r= 1:nr

for c= 1:nc-ns+1if strcmpi( str , A(r, c:c+ns-1) )==1

D(r, c:c+ns-1)= Xs;end

endend

AU s M A T L A Be

i n t h a t l a b .

1 2 3 … 8 9 10 1211

X XXXs

Returns an array of type doubleChanges the type to char

Case insensitive comparison of strings

Page 6: Previous Lecture: Today’s Lecture

Lecture 19 10

Array vs. Cell Array

Simple array Each component stores one scalar. E.g., one char,

one double, or one uint8 value All components have the same type

Cell array Each cell can store something “bigger” than one

scalar, e.g., a vector, a matrix, a string (vector of chars)

The cells may store items of different types

‘C’‘S’ ‘1’ ‘1’‘1’ ‘2’‘ ’

‘C’‘S’ -11.1 12-71.1812

Page 7: Previous Lecture: Today’s Lecture

Lecture 18 11

1-d and 2-d examples …

3.1

2

-1

9

1.1

‘c’ ‘o’ ‘m’ ‘ ’ ‘s’

‘1’ ‘1’ ‘1’ ‘2’ ‘ ’

‘ ’ ‘ ’ ‘L’ ‘A’ ‘B’

‘M’ ‘a’ ‘t’ ‘ ’ ‘ ’

Vectors and matrices store values of the same type in all components

Cell array: individual components may contain different types of data

.4‘M’ -1 7

.91

5

-4 -1

7

‘ ’‘.’ ‘ ’

‘m’‘c’ ‘o’

3 × 2 cell array

4 x 5matrix5 x 1

matrix

Page 8: Previous Lecture: Today’s Lecture

Cell Arrays of Strings

C= { ‘Alabama’,’New York’,’Utah’}

C ‘Alabama’ ‘New York’ ‘Utah’

C= { ‘Alabama’;’New York’;’Utah’}

‘Alabama’

‘New York’

‘Utah’

C

1-d cell array of strings

M= [‘Alabama ’; ...‘New York’; ...‘Utah ’]

‘A’ ‘l’ ‘a’ ‘b’ ‘a’

‘N’ ‘e’ ‘w’ ‘ ‘ ‘Y’

‘U’ ‘t’ ‘h’

‘m’ ‘a’

‘o’ ‘r’ ‘k’

‘ ‘

‘ ‘‘a’ ‘ ‘‘ ‘‘ ‘

M

Contrast with 2-d array of characters

Page 9: Previous Lecture: Today’s Lecture

Lecture 18 13

Use braces { } for creating and addressing cell arrays

Matrix

Create

m= [ 5, 4 ; …1, 2 ; …0, 8 ]

Addressing

m(2,1)= pi

Cell Array

Create

C= { ones(2,2), 4 ; …‘abc’ , ones(3,1); …9 , ‘a cell’ }

Addressing

C{2,1}= ‘ABC’C{3,2}= pidisp(C{3,2})

Page 10: Previous Lecture: Today’s Lecture

Lecture 18 14

Creating cell arrays…

C= {‘Oct’, 30, ones(3,2)};

is the same asC= cell(1,3); % not necessaryC{1}= ‘Oct’;C{2}= 30;C{3}= ones(3,2);

You can assign the empty cell array: D = {}

Page 11: Previous Lecture: Today’s Lecture

Lecture 18 15

D{1} = ‘A Hearts’;D{2} = ‘2 Hearts’;

:D{13} = ‘K Hearts’;D{14} = ‘A Clubs’;

:D{52} = ‘K Diamonds’;

Example: Represent a deck of cards with a cell array

But we don’t want to have to type all combinations of suits and ranks in creating the deck… How to proceed?

Page 12: Previous Lecture: Today’s Lecture

Lecture 18 16

suit = {‘Hearts’, ‘Clubs’, …‘Spades’, ‘Diamonds’};

rank = {‘A’,‘2’,’3’,’4’,’5’,’6’,…’7’,’8’,’9’,’10’,’J’,’Q’,’K’};

Then concatenate to get a card. E.g.,

str = [rank{3} ‘ ’ suit{2} ];D{16} = str;

So D{16} stores ‘3 Clubs’

Make use of a suit array and a rank array …

Page 13: Previous Lecture: Today’s Lecture

Lecture 18 17

suit= {’Hearts’,’Clubs’,’Spades’,’Diamonds’};rank= {’A’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,...

’10’,’J’,’Q’,’K’};i= 1; % index of next cardfor k= 1:4

% Set up the cards in suit kfor j= 1:13

D{i}= [ rank{j} ' ' suit{k} ];i= i + 1;

endend

To get all combinations, use nested loops

See function CardDeck

Page 14: Previous Lecture: Today’s Lecture

Lecture 18 18

suit= {’Hearts’,’Clubs’,’Spades’,’Diamonds’};rank= {’A’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,...

’10’,’J’,’Q’,’K’};i= 1; % index of next cardfor k= 1:4

% Set up the cards in suit kfor j= 1:13

D{i}= [ rank{j} ' ' suit{k} ];i= i + 1;

endend

function D = CardDeck()% D is 1-by-52 cell array of strings that define a card deck

Page 15: Previous Lecture: Today’s Lecture

Lecture 19 30

Application of cell array: sort data in a file

File statePop.txt contains state population data sorted alphabetically by state:

Cols 1-14: State nameCols 16-24: Population (millions)

statePop.txt

Alabama 4557808Alaska 663661Arizona 5939292Arkansas 2779154California 36132147Colorado 4665177

: :: :

Washington 6287759West Virginia 1816856Wisconsin 5536201Wyoming 509294

Page 16: Previous Lecture: Today’s Lecture

Lecture 19 31

A detailed sort-a-file example

File statePop.txt contains state population data sorted alphabetically by state. Create a new file

statePopSm2Lg.txtthat is structured the same as statePop.txtexcept that the states are ordered from smallest to largest according to population.

• Need the pop as numbers for sorting.

• Can’t just sort the pop—have to maintain association with the state names.

Alabama 4557808Alaska 663661Arizona 5939292Arkansas 2779154California 36132147Colorado 4665177

: :: :

statePop.txt

Page 17: Previous Lecture: Today’s Lecture

Lecture 19 32

First, read the file and store each line in a cell of a cell array

C = file2cellArray('StatePop');

Page 18: Previous Lecture: Today’s Lecture

Lecture 19 35

In a file there are hidden “markers”

Carriage return marks the end of a line

eof marks the end of a file

Alabama 4557808Alaska 663661Arizona 5939292

stateData.txt

Page 19: Previous Lecture: Today’s Lecture

Lecture 19 36

Read data from a file

1. Open a file2. Read it line-by-line until end-of-file3. Close the file

function fopen

functions fgetl, feof

function fclose

Page 20: Previous Lecture: Today’s Lecture

Lecture 19 37

1. Open the file

fid = fopen(‘statePop.txt’, ‘r’);

An open file has a file ID, here stored in variable fid

Built‐in functionto open a file

Name of the file opened.  txt and dat are common file name extensions for plain text files ‘r’ indicates 

that the filehas been opened forreading 

Page 21: Previous Lecture: Today’s Lecture

Lecture 19 38

2. Read each line and store it in cell array

fid = fopen(‘statePop.txt’, ‘r’);

k= 0;while ~feof(fid)

k= k+1;Z{k}= fgetl(fid);

end

False until end-of-file is reached

Get the next line.(Each call gets one line; you cannot make it skip lines or go to a specific line.)

Page 22: Previous Lecture: Today’s Lecture

Lecture 19 39

3. Close the file

fid = fopen(‘statePop.txt’, ‘r’);

k= 0;while ~feof(fid)

k= k+1;Z{k}= fgetl(fid);

end

fclose(fid);

Page 23: Previous Lecture: Today’s Lecture

Lecture 19 40

function CA = file2cellArray(fname)% fname is a string that names a .txt file% in the current directory.% CA is a cell array with CA{k} being the % k-th line in the file.

fid= fopen([fname '.txt'], 'r');k= 0;while ~feof(fid)

k= k+1;CA{k}= fgetl(fid);

endfclose(fid);

Page 24: Previous Lecture: Today’s Lecture

Lecture 19 41

Page 25: Previous Lecture: Today’s Lecture

Lecture 19 43

Page 26: Previous Lecture: Today’s Lecture

Lecture 19 44

Next, get the populations into a numeric vector

C = file2cellArray('StatePop');n = length(C);pop = zeros(n,1);for i=1:n

S = C{i};pop(i) = str2double(S(16:24));

end Converts a string representing a numeric value (digits, decimal point, spaces) to the numeric value scalar of type double. E.g., x=str2double(’ -3.24 ’) assigns to variable x the numeric value -3.2400…

Page 27: Previous Lecture: Today’s Lecture

Lecture 19 46

Page 28: Previous Lecture: Today’s Lecture

Lecture 19 47

Built-In function sort

Syntax: [y,idx] = sort(x)

10 20 5 90 15

5 10 15 20 90

3 1 5 2 4

X:

y:

idx:

y(1) = x(3) = x(idx(1))

Page 29: Previous Lecture: Today’s Lecture

Lecture 19 48

Built-In function sort

Syntax: [y,idx] = sort(x)

10 20 5 90 15

5 10 15 20 90

3 1 5 2 4

X:

y:

idx:

y(2) = x(1) = x(idx(2))

Page 30: Previous Lecture: Today’s Lecture

Lecture 19 52

Built-In function sort

Syntax: [y,idx] = sort(x)

10 20 5 90 15

5 10 15 20 90

3 1 5 2 4

X:

y:

idx:

y(k) = x(idx(k))

Page 31: Previous Lecture: Today’s Lecture

Lecture 19 54

Sort from little to big

% C is cell array read from statePop.txt% pop is vector of state pop (numbers)[s,idx] = sort(pop);Cnew = cell(n,1);for i=1:length(Cnew)

ithSmallest = idx(i);Cnew{i} = C{ithSmallest};

end

Page 32: Previous Lecture: Today’s Lecture

Lecture 19 55

Wyoming 509294Vermont 623050North Dakota 636677Alaska 663661South Dakota 775933Delaware 843524Montana 935670

: :: :

Illinois 12763371Florida 17789864New York 19254630Texas 22859968California 36132147

Cnew