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.
concen, shown below, operates on an array of structures with specific characteristics. Its arguments must contain the fields
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
|Applying Functions and Operators||Organizing Data in Structure Arrays|
© 1994-2005 The MathWorks, Inc.