Having trouble with my conditional if statement for a structure
4 次查看(过去 30 天)
显示 更早的评论
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:
- 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.
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
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!