plato/struct_arrays.m

40 lines
1.2 KiB
Matlab

clear
% create a struct array
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
% add an entry to the struct array
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
% if the index is not specified, patient.field returns
% the fields of all its elements as multiple return values
[name1, name2] = patient.name;
assert(isequal(name1, 'John Doe'));
assert(isequal(name2, 'Ann Lane'));
% creates a new records 'age'; this will be created in all the other
% entries; fields not specified here are set to []
patient(3).name = 'New Name';
patient(3).age = 21;
% creates a new struct array with the same layout
customer(1).name = 'Enrico';
customer(1).billing = 30.0;
customer(1).test = [];
customer(1).age = 25;
% acceess fields indirectly
field = "name";
assert(isequal(customer(1).(field), 'Enrico'));
% concatenates patient and customer to create a new struct array
v = [patient customer]; % or [patient, customer]
% can also concatenate in a matrix layout: this create a 2x2 struct matrix
M = [patient(1:2); [customer patient(3)]];
assert(all(M(2, 1).name == 'Enrico'));