Summary

This document is a set of lecture notes on structures in MATLAB, suitable for undergraduates in aerospace engineering. The notes cover topics such as creating and accessing structures, nested structures, arrays of structures, and using structures in functions and are part of a larger programming unit.

Full Transcript

UNIT 5. STRUCTURES P R O G R A M M I N G. A E R O S PA C E E N G I N E E R I N G PA U L A D E T O L E D O. Y E A R 2 0 2 2 - 2 0 2 3 CONTENTS 1. Structures 2. Nested structures 3. Arrays as fields of a structure 4. Arrays of structures (structures as elements of an array)...

UNIT 5. STRUCTURES P R O G R A M M I N G. A E R O S PA C E E N G I N E E R I N G PA U L A D E T O L E D O. Y E A R 2 0 2 2 - 2 0 2 3 CONTENTS 1. Structures 2. Nested structures 3. Arrays as fields of a structure 4. Arrays of structures (structures as elements of an array) – Pre-allocating arrays of structures 5. Functions: structures as function parameters Annex (only for reference) – Other structured data types in MatLab Cells Tables 1. STRUCTURES MATLAB DATA TYPES (CLASSES) all variables in Matlab are arrays Structured information Scalars: atomic information, single values In matlab, scalars are 1x1 arrays STRUCTURES A structure is a data type that groups heterogenous but logically related data using data containers called fields – used to organize complex information in a program – logically related variables can be treated as a unit instead of as separate entities Differently from arrays, each element (field) can be of a different data type Flight number – Example : store flight information Origin airport flight Destination airport Ticket price BUILDING STRUCTURES IN MATLAB Explicit: using function struct (recommended) myFlight = struct('origin', 'MAD',... 'destination', 'JFK',... 'number','IB345',... 'ticketPrice', 145.99); Field names (in quotes) Field values Implicit: extend by assignment – see later ACCESSING FIELDS: THE DOT OPERATOR To access a field of a structure, we use 1. dot operator (.) 2. field name Differently to arrays where elements are accessed using the index Example: assign values to a field myFlight.origin = 'BCN' myFlight.destination = 'LAS' myFlight.number ='EK499'; BUILDING OR EXTENDING A STRUCTURE BY ASSIGNMENT MatLab will build a structure if you specify a variable with fields myFlight.origin = 'MAD'; MatLab will extend the structure if a value is assigned to a new field myFlight.destination= 'JFK'; myFlight.number ='IB345'; myFlight.ticketPrice = 145.99; myFlight.airline ='Iberia'; Handle with care! – Good programming practice: define structures using struct – Extending by assignment will not work in other programming languages DISPLAYING STRUCTURES disp() function: default format origin: 'MAD' destination: 'JFK' disp(myFlight) number: 'IB345' ticketPrice: 145.9900 airline: 'Iberia' fprintf – print with format fprintf('Info:\nFlight %s ',myFlight.number); fprintf('from %s to %s\n',myFlight.origin,myFlight.destination); fprintf('Price: %.2f euro\n',myFlight.ticketPrice); fprintf('Airline: %s\n',myFlight.airline); Info: Flight IB345 from MAD to JFK Price: 145.99 euro Airline: Iberia FIELDS OF A STRUCTURE Fields can contain any type of data: – scalar (int, double, char), – structured A structure (nested structures) An array 10 2. NESTED STRUCTURES NESTED STRUCTURES Structures where a field is another structure Flight number flight Origin airport Destination airport ground speed latitude Flight details position longitude altitude myFlight.details.position.altitude =11582; myFlight.details.groundspeed=959; DECLARING NESTED STRUCTURES IN MATLAB Flight number flight Origin airport Destination airport ground speed latitude Flight details position longitude altitude position = struct ('altitude',0,'latitude',0,'longitude',0); details = struct ('groundspeed',0,'position',position); myFlight = struct('origin', 'MAD',... myFLigh2 = struct('origin', 'MAD',... 'destination', 'JFK',... 'destination', 'JFK',... 'number','IB345',... 'number','IB345'); 'details', details); myFlight.details.position.altitude =11582; myFlight.details.groundspeed=959; 3. A R R AY S A S F I E L D S OF A STRUCTURE ARRAYS AS FIELDS OF A STRUCTURE name 'Jhon' surname 'Smith' student age 18 marks 5.0 5.2 6.0 8.9 9.0 10.0 % build student =struct ('name','Jhon',... 'surname' ,'Smith',... 'age',18,... 'marks', [5.0,5.2,6.0,8.9,9.0,10.0]... ); % change values student.name = 'Jane' student.marks(6)=10; 4. A R R AY S O F STRUCTURES ARRAYS OF STRUCTURES Vectors or matrices whose elements are structures Specially useful to store and manage information – We seldom use one structure on its own, much more common vector of structures Example: vector of students to store data from a class name 'Jhon' name ‘Jane' name ‘Bill' surname 'Smith' surname Lock' surname 'Klee' age 18 age 18 age 18 marks 5.0 5.2 6.0 8.9 9.0 10.0 marks 10.0 10.0 6.0 8.9 9.0 10.0 marks 5.0 7.2 9.0 8.9 7.0 10.0 students(1) students(2) students(3) ACCESSING DATA IN A ARRAY OF STRUCTURES students(3).name = 'Bill' students(3).marks(1)= 5.0; Brackets to identify the position in the vector Dot notation to identify the field VECTOR OF STRUCTURES: EXAMPLE 2 - PRODUCTS vProducts name "cocacola" name “fanta" name “trina" name “pepsi" amount 10 amount 3 amount 1 amount 12 unit price 5.95 unit price 7.95 unit price 3.95 unit price 7.95 % read data for i=1:4 vProducts(i).name = input('Enter product name:..','s'); vProducts(i).amount = input('Enter amount of items:..’); vProducts(i).price = input('Enter price:..'); end % compute stock value totalStockValue=0; for i=1:4 totalStockValue= totalStockValue +... vProducts(i).price * vProducts(i).amount; end P R E A L L O C AT E A N D I N I T I A L I Z E V E C TO R S O F S T RU C T U R E S 20 PREALLOCATE AND INITIALIZE VECTORS OF STRUCTURES Best practice – Pre-allocate memory – Initialise contents as appropriate Why? – Memory requirements Structure arrays do not require completely contiguous memory. each field does require contiguous memory For large arrays, incrementally increasing the number of fields or the number of elements in a field results in bad performance or even out of Memory errors. PREALLOCATION OF VECTOR OF STRUCTURES Build a structure using struct and intial values Use that structure to initialize all elements of a vector name "" name "" name "" name "" amount 0 amount 0 amount 0 amount 0 unit price 0 unit price 0 unit price 0 unit price 0 vProducts % build structure with initial values product=struct('name',"",... 'amount',0,... 'price',0); % assing this structure to ALL elements of a vector vProducts(1,1:4)=product; PREALLOCATION Same idea, all in one line of code name "" name "" name "" name "" amount 0 amount 0 amount 0 amount 0 unit price 0 unit price 0 unit price 0 unit price 0 vProducts % build structure with initial values AND assing this structure to ALL elements of a vector vProducts(1,1:4)= =struct('name',"",... 'amount',0,... 'price',0); PREALLOCATION Another option: Initialize fields to the empty array name [] name [] name [] name [] amount [] amount [] amount [] amount [] unit price [] unit price [] unit price [] unit price [] vProducts % create and preallocate structure – option one % initialice to empty array vProducts(1,1:4)=struct('price',[],... 'amount',[],... 'name',[]); PREALLOCATION: INITIAL CAN BE MATRICES students (1,1:40) = struct('name', "",... 'surname' , "",... 'age’,0,... 'marks', zeros(1,6)); name "" name "" name "" surname "" surname "" surname "" age 0 age 0 … age 0 marks 0 0 0 0 0 0 marks 0 0 0 0 0 0 marks 0 0 0 0 0 0 students(1) students(40) PREALLOCATION: INTIALIZATION VALUES CAN BE STRUCTURES address = struct('city','','country','Spain'); students(1,1:maxStudents) = struct('name',"",... 'surname',"",... 'address', address,... % address is a structure 'marks',zeros(1,nSubjects)); disp(students) name surname address marks student(1).address.country "" "" 1x1 struct [0,0,0,0,0,0] "" "" 1x1 struct [0,0,0,0,0,0] spain "" "" 1x1 struct [0,0,0,0,0,0] FUNCTIONS: STRUCTURES AS PARAMETERS 34 ARRAYS AND STRUCTURES AS PARAMETERS OF FUNCTIONS Arrays can be used as parameters of functions Structures can be used as parameters of functions STRUCTURE AS PARAMETER: EXAMPLE %% main script myCustomer = struct('name','Jhon',... 'surname','Doe',... 'cardNumber',103324); Cardnumber: 103324 printCustomer(myCustomer) Name : Jhon Surname : Doe %% function function printCustomer(customer) % input data: customer (structure 1x1) % output data: none % task: display data of the customer fprintf('Cardnumber: %i\n',customer.cardNumber); fprintf('\tName : %s\n',customer.name); fprintf('\tSurname : %s\n',customer.surname); end VECTOR OF STRUCTURES AS PARAMETER: EXAMPLE 1 %% main script nCustomers =100; vCustomers(1,1:nCustomers) = struct(... 'name','',... 'surname','',... 'cardNumber',0); printAllCustomers(vCustomers,nCustomers) %% function function printAllCustomers(v,n) % v is a vector of structures of type customer % n is the number of elements in the vector to print fprintf('Showing all registered customers\n'); for i=1:n % reuse function from previous slide printCustomer(v(i)); end end VECTOR OF STRUCTURES AS PARAMETER: EX AMPLE 2 function [flights]= randInitFlights(flights,n) % this function returns a vector of structures flight of size 1xn % where each structure is assigned random values airline = ["IB","BA","ZB"]; %vector of strings with airline names for i=1:n company = randi([1,3]); % company=random value 1 2 3 number = randi([100,999]); % random flight number % concatenate airline name and flight number to generate flight ID flights(i).flightID = strcat(airline(company), num2str(number)); % fuel cost and consumed fuel flights(i).fuel_unit_cost=50; flights(i).consumed_fuel = randi([50 200]); flights(i).num_first_class= randi([0 20]); flights(i).num_second_class= randi([10 130]); flights(i).delay_hours = randi([0 4]); end end ANNEX OT H E R S T RU C T U R E D DATA T Y P E S I N M AT L A B : C E L L A R R AYS A N D TA B L E S TABLES Only for reference price amount name Tables store column-oriented (tabular) data 15.95 10 "cocacola" Such as columns from a spreadsheet (excel) 17.95 30.95 3 1 “fanta" “trina" Table variables can have different data types 27.95 12 “pepsi" and sizes as long as all variables have the same number of rows Tables can be indexed by name or numeric index – products(1, 'price') =19.5 – products(1,1) =19.5 If you have rectangular data that is homogeneous in each variable, consider using a table. EXAMPLE:TABLES T=5×6 table LastName Age Smoker Height Weight BloodPressure {'Sanchez'} 38 true 71 176 93 {'Johnson'} 43 false 69 163 77 {'Li' } 38 true 64 131 83 {'Diaz' } 40 false 67 133 75 {'Brown' } 49 true 64 119 80 CELL ARRAYS Only for reference A cell array is a data type with indexed data containers called cells, where each cell can contain any type of data. Similar to an array, but elements are not the same type Cell arrays can be indexed just as a standard array When to use cell arrays? – lists of character vectors of different lengths, – mix of strings and numbers, or numeric arrays of different sizes CELL ARRAY EXAMPLE Only for reference myCell = {1,2,3; 'hello', rand(5,10,2), [11; 22; 33]} myCell= 2×3 cell array {[ 1]} {[ 2]} {[ 3]} {'hello'} {5x10x2 double} {3x1 double} braces { } to declare cell arrays UNIT 5. STRUCTURES PROGRAMMING

Use Quizgecko on...
Browser
Browser