Having trouble with my conditional if statement for a structure

조회 수: 4 (최근 30일)
AStar
AStar 2019년 11월 22일
댓글: AStar 2019년 11월 23일
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

채택된 답변

Darshan Sen
Darshan Sen 2019년 11월 23일
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. :)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by