Find Min, Max and Avg of a field

1 次查看(过去 30 天)
I am new to the matlab. So please reply even if my question is trivial.
Here is just a sample of code
Car.id = '';
Car.mileage = 0;
Car.model = '';
Car.maxSpeed = 0;
carMatrix=[];
for i = 1:3
Car.id = strcat('A',num2str(i));
Car.mileage = 15 + i;
Car.model = strcat('XYZ',num2str(i));
Car.maxSpeed = 100 + 10*i;
carMatrix = [carMatrix; Car];
end
In actual scenario I am giving values to the Car fields by reading it from a excel file and there are more that 300 Car values inside the excel file.
Here are few things that I want to calculate
1) Find maximum and minimum value of the 'mileage' field of all the Car in carMatrix.
2) Find Car object having maximum and minimum value of mileage
3) Find average 'mileage' (i.e. (Car1.mileage + Car2.mileage + Car3.mileage) / 3)
4) Suppose in some scenario I have following data Car2.mileage = 18 and Car3.mileage = 18. So if I want to find out all the Car objects whose mileage is 18, then it should return Car2 and Car3 along with their rownumber.
I do not want to use loop for these calculation. Is there any built in function of matlab for these things.
Thanks

采纳的回答

Image Analyst
Image Analyst 2016-8-6
Don't use carMatrix. Just index. And the answers to your questions follow the fixed code where you create the structure array. See below:
Car.id = '';
Car.mileage = 0;
Car.model = '';
Car.maxSpeed = 0;
carMatrix=[];
for i = 1:3
Car(i).id = strcat('A',num2str(i));
Car(i).mileage = 15 + i;
Car(i).model = strcat('XYZ',num2str(i));
Car(i).maxSpeed = 100 + 10*i;
end
% 1) Find maximum and minimum value of the 'mileage' field of all the Car in carMatrix.
% 2) Find Car object having maximum and minimum value of mileage
% 3) Find average 'mileage' (i.e. (Car1.mileage + Car2.mileage + Car3.mileage) / 3)
allMileages = [Car.mileage] % Strings all mileages together into one vector for convenience.
[maxMileage, indexOfMaxCar] = max(allMileages)
[minMileage, indexOfMinCar] = min(allMileages)
averageMileage = mean(allMileages)
% 4) Suppose in some scenario I have following data Car2.mileage = 18 and Car3.mileage = 18.
% So if I want to find out all the Car objects whose mileage is 18,
Car(2).mileage = 18;
Car(3).mileage = 18;
allMileages = [Car.mileage]
mileageIs18 = find(allMileages == 18)
% then it should return Car2 and Car3 along with their rownumber.
for k = mileageIs18
Car(k) % Echo to command window
end

更多回答(1 个)

Azzi Abdelmalek
Azzi Abdelmalek 2016-8-6
[maxval,index]=max([carMatrix.mileage])
  1 个评论
Anil Verma
Anil Verma 2016-8-6
Thanks
I am able to calculate max, min and average using the expression mentioned by you. But still I am not able to get all the Cars and their row number having same mileage(Question 4). Can you please me on this also.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Model Scripting 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by