MATLAB: Find Min, Max and Avg of a field

avgmatrixmaxmin

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

Best Answer

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