Having trouble with my conditional if statement for a structure

5 views (last 30 days)
Im trying to do this exercise from my programming textbook however my code is not working. If someone could comment on why its not working and what I need to change. Ive attached my code.
NOTE: Im pretty sure this will work
avgheight = sum([subjects.height])/length(subjects);
avgweight = sum([subjects.weight])/length(subjects);
and then instead of using mean(subjects.height) I would put avgheight
But I dont understand why the mean function is not equivalent to that?
Whats the point of the built in mean function if I still have to make matlab compute the average manually?
IF SOMEONE COULD TELL ME HOW TO GET THE MEAN FUNCTION TO WORK
Here is the question from the book:
  1. 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)
  2. ans =name: 'Joey'
  3. sub_id: 111
  4. height: 6.7000
  5. weight: 222.2000
  6. 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.
subjects(1)=struct('name','Joey','sub_id',111,'height',6.7,'weight',222.2);
subjects(2)=struct('name','Kyle','sub_id',119,'height',6.2,'weight',210);
subjects(3)=struct('name','Andrei','sub_id',125,'height',6.1,'weight',225);
n=length(subjects);
for i=1:n
if subjects.height(i) < mean(subjects.height) || subjects.weight(i) < mean(subjects.weight)
%print the names of those who are eligible
fprintf('The names of those eligible are: %s %s %s\n',subjects(i).name)
end
end

Accepted Answer

Darshan Sen
Darshan Sen on 23 Nov 2019
Hello AStar.
You were very close to solving this problem. You had to use the square brackets in the function mean just like you used it in function sum.
>> subjects(1)=struct('name','Joey','sub_id',111,'height',6.7,'weight',222.2);
subjects(2)=struct('name','Kyle','sub_id',119,'height',6.2,'weight',210);
subjects(3)=struct('name','Andrei','sub_id',125,'height',6.1,'weight',225);
>> mean_of_height = mean([subjects.height])
mean_of_height =
6.3333
>> mean_of_weight = mean([subjects.weight])
mean_of_weight =
219.0667
Hope this helps. :)

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!