
























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Class: Introduction to Computing Using MATLAB; Subject: Computer Science; University: Cornell University; Term: Spring 2009;
Typology: Study notes
1 / 32
This page cannot be seen from the preview
Don't miss anything!

























^
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);
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
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)
and
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)
and
are
points
(structure).
Draws
a
line
segment
connecting
and
Color
is
specified
by
c.
plot([P.x
Q.x],[P.y
Q.y],c)
Another function that has structure parameters
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
x
y
MakePoint(.50,.86)
March 31, 2009
Lecture 19
x
y
MakePoint(-1.0,0.0)
March 31, 2009
Lecture 19
x
y
MakePoint(-.50,-.86)