Docsity

Structures, Structure Array, Structure with Array Fields - Slides | CS 1112, Study notes of Computer Science

Partial preview of the text

Download Structures, Structure Array, Structure with Array Fields - Slides | CS 1112 and more Study notes Computer Science in PDF only on Docsity!

„^

Previous Lecture:^ „

Cell arrays „^

Today’s Lecture:^ „

Structures „ Structure array (an array of structures) „ A structure with array fields „^

Announcement:^ „

Project 4 due tonight at 11pm „ Section this week in the computer lab (UP B7) „ Catch-up review session W 5:45-6:45. Location TBA.

March 31, 2009

Lecture 19

„^

A point in the plane has an x coordinate and ycoordinate. „^

If a program manipulates lots of points, there willbe lots of x’s and y’s. „^

Anticipate clutter. Is there a way to “package”the two coordinate values? Data are often related

March 31, 2009

Lecture 19

Simple example p1 = struct(‘x’,3,’y’,4);p2 = struct(‘x’,-1,’y’,7);D = sqrt((p1.x-p2.x)^2 + (p1.y-p2.y)^2);

D

is distance between two points. p1.x,

p1.y,

p2.x,

p2.y

participating

as variables—because they are

.

p x

y

March 31, 2009

Lecture 19

Creating a structure (by direct assignment)

p1 = struct(‘x’,3,’y’,4);p

is a structure. The structure has two fields.Their names are

x

and

y

They are assigned the values 3 and 4.

March 31, 2009

Lecture 19 p

x

y

A

p1.x

p1.y;

Assigns the value 7 to A

Accessing the fields in a structure

March 31, 2009

Lecture 19 p

x

y

p1.x = p1.y^2;

Assigns the value 16 to p1.x

Assigning to a field in a structure

March 31, 2009

Lecture 19

Legal/Illegal maneuvers Q = struct(‘x’,5,’y’,6)R = Q

% Legal. R is a copy of Q

S = (Q+R)/

% Illegal. Must access the% fields to do calculations

P = struct(‘x’,3,’y’)

% Illegal. Args must be% in pairs (field name% followed by field% value)

P = struct(‘x’,3,’y’,[])

% Legal. Use [] as

P.y = 4

% place holder

March 31, 2009

Lecture 19

function

d

dist(P,Q)

P

and

Q

are

points

(structure).

d

is

the

distance

between

them.

d

sqrt((P.x-Q.x)^

(P.y-Q.y)^2);

Structures in functions

March 31, 2009

Lecture 19

function

DrawLine(P,Q,c)

P

and

Q

are

points

(structure).

Draws

a

line

segment

connecting

P

and

Q.

Color

is

specified

by

c.

plot([P.x

Q.x],[P.y

Q.y],c)

Another function that has structure parameters

  • March 31,
  • Lecture

March 31, 2009

Lecture 19

Structure Arrays^ „

An array whose components are structures „ All the structures must be the same (have thesame fields) in the array „ Example: an array of points (point structures)

.86^ y

.5^ x

.91^ y

1.5^ x

.28^ y

.4^ x

1.8^ y

2.5^ x

P

P(1)

P(2)

P(3)

P(4)

March 31, 2009

Lecture 19

P(1)

x

y

An Array of Points

P(1)

MakePoint(.50,.86)

March 31, 2009

Lecture 19

P(3)

x

y

An Array of Points

P(3)

MakePoint(-1.0,0.0)

March 31, 2009

Lecture 19

P(4)

x

y

An Array of Points

P(4)

MakePoint(-.50,-.86)