structs ------------------------------------------------------------------------------- (1) General: Structure Arrays + special kind of array + holds arrays inside elements + arrays may be different types! + addresses elements by names called FIELDS + SAs usually 1-D but can be multi-dim ----------------------------------------------------------------------------- (2) Creating + Just make assignments + to store values use the $.$ operator syntax: name.field=value >> A.fn = 'ben'; >> A.ln = 'stein'; >> A.id = 4321 A = fn: 'ben' ln: 'stein' id: 4321 + Note: - MATLAB will display a reference if the field is not 1-D - Try $A.x = [1:3;3:5]$ and then displaying $A$ >> A.x = [1:3;3:5] ----------------------------------------------------------------------------- (3) Retrieve values Use name.field >> A.fn ----------------------------------------------------------------------------- (4) Fields can be any other data structure, including another SA Create a new SA >> B.tests = [99 88] >> B.projects = [10 10 10]; >> B B = tests: [99 88] projects: [10 10 10] Create new field of A called $scores$ Assign scores in $B$ to $A$ >> A.scores = B A = fn: 'ben' ln: 'stein' id: 4321 x: [2x3 double] scores: [1x1 struct] Notes: + $scores$ and $x$ values NOT 1-D, so ML uses pointers + But, values are still there! + Access particular value name.(substructure access) means name.name.field >> A.scores.tests ans = 99 88 ----------------------------------------------------------------------------- (5) Additional Things + Useful help: help struct help rmfield help getfield help setfield + Preallocation >> SA1 = struct('x',0,'y',1) SA1 = x: 0 y: 1 + Removing fields - ML's SAs have a feature not common to other languages - Entering $rmfield$ will remove the NAME and CONTENTS of a field >> A = rmfield(A,'x') A = fn: 'ben' ln: 'stein' id: 4321 scores: [1x1 struct] ----------------------------------------------------------------------------- (6) Array of Structures + can create an array of SAs by "adding" another SA - start with initial SA and make another - give 1 or more fields a value - ML automatically creates a new SA - empty fields represented as empty array $[]$ >> A(2).fn = 'gene'; >> A(2) ans = fn: 'gene' ln: [] id: [] x: [] scores: [] + What's an array of SAs??? >> A A = 1x2 struct array with fields: fn ln id x scores + to get individual SAs, enter $A(1),A(2)$ -----------------------------------------------------------------------------