5- Answer:
clear;
%{
A script stores information on potential subjects for an experiment in a vector
of structures called subjects. The following shows an example of what the contents
might be:
>> subjects(1)
ans =
name: 'Joey'
sub_id: 111
height: 6.7000
weight: 222.2000
For this particular experiment, the only subjects who are eligible are those
whose height or weight is lower than the average height or weight of all
subjects. The script will print the names of those who are eligible. Create a
vector with sample data in a script, and then write the code to accomplish
this. Don't assume that the length of the vector is known; the code should be
general.
%}
%% create structure array
subjects(3) = struct('name', [], 'sub_id', [], 'height', [], 'weight', []);
%% fill in subjects info
subjects(1) = struct('name', 'Joey', 'sub_id', 111, 'height', 6.7, 'weight', 222.2);
subjects(2) = struct('name', 'Moe', 'sub_id', 112, 'height', 7.1, 'weight', 199);
subjects(3) = struct('name', 'Mahmoud', 'sub_id', 113, 'height', 6.1, 'weight', 201);
%% find avg height & weight
havg = mean( [subjects.height] );
wavg = mean( [subjects.weight] );
%% create list of persons lower than avg height or wght
count = 0;
for ii = 1:length(subjects),
hh = subjects(ii).height;
ww = subjects(ii).weight;
if (hh < havg)||(ww < wavg),
count = count + 1;
subj(count) = subjects(ii);
end
end
%% display the names in the list
for ii = 1:length(subj)
fprintf('%d, %s\n',ii,subj(ii).name);
end
Expected Output
1, Joey 2, Mahmoud
Code Explanation
Step 1: Initialize Structure Array
The code pre-allocates a structure array with 3 elements, each having fields for name, sub_id, height, and weight.
Step 2: Populate Subject Data
Three subjects are created with their respective information using the struct function.
Step 3: Calculate Averages
The mean height and weight across all subjects are calculated using vectorized operations and the mean function.
Step 4: Filter Eligible Subjects
A loop iterates through all subjects, checking if each subject's height OR weight is below the calculated average.
Step 5: Display Results
The names of eligible subjects are printed with their corresponding numbers in the eligibility list.