Programming |
Writing Functions to Operate on Structures
You can write functions that work on structures with specific field architectures. Such functions can access structure fields and elements for processing.
Note When writing M-file functions to operate on structures, you must perform your own error checking. That is, you must ensure that the code checks for the expected fields. |
As an example, consider a collection of data that describes measurements, at different times, of the levels of various toxins in a water source. The data consists of fifteen separate observations, where each observation contains three separate measurements.
You can organize this data into an array of 15 structures, where each structure has three fields, one for each of the three measurements taken.
The function concen
, shown below, operates on an array of structures with specific characteristics. Its arguments must contain the fields lead
, mercury
, and chromium
:
function [r1, r2] = concen(toxtest); % Create two vectors. r1 contains the ratio of mercury to lead % at each observation. r2 contains the ratio of lead to chromium. r1 = [toxtest.mercury] ./ [toxtest.lead]; r2 = [toxtest.lead] ./ [toxtest.chromium]; % Plot the concentrations of lead, mercury, and chromium % on the same plot, using different colors for each. lead = [toxtest.lead]; mercury = [toxtest.mercury]; chromium = [toxtest.chromium]; plot(lead, 'r'); hold on plot(mercury, 'b') plot(chromium, 'y'); hold off
Try this function with a sample structure array like test
:
test(1).lead = .007; test(2).lead = .031; test(3).lead = .019; test(1).mercury = .0021; test(2).mercury = .0009; test(3).mercury = .0013; test(1).chromium = .025; test(2).chromium = .017; test(3).chromium = .10;
Applying Functions and Operators | Organizing Data in Structure Arrays |
© 1994-2005 The MathWorks, Inc.