matlab 8.4 - Quiz Average We created a vector of structures in the following for
ID: 3598626 • Letter: M
Question
matlab
8.4 - Quiz Average We created a vector of structures in the following format (Note: every element in vec is a structure with two fields: id_no, which is an integer, and quiz, which is a vector of doubles): vec quiz id no 7.5 5.5 6 6.5 37 24 4 7 Modify the function mysort() below to sort this vector in ascending order based on the quiz average. For example, if the vector stores the values shown above, this would be an example of calling mysort) >> sortvec = mysort (vec); >> for i 1:4 fprint f (.2d ave : %.1f ', sortvec (1).id-no , mean (sortvec(i).quiz)) end 33 ave: 6. 24 ave: 7.0 44 ave: 7.5 37 ave: 8.0 Your Function C Reset MATLAB Documentation 1 function outv mysort (vec) 3 for 4 5 i = ind low = 1; for 1: length(vec)-1 j=1+1:length(vec) if vec(j)Explanation / Answer
The input vector with averages before and after have been provided below a output:
The sort function was already provided. We just used the mean function to find the mean of these. and sorted accordingly.
To swap we need to swap id as well as the quiz vector so that they lie correspondingly in the vector.
************************************************************************
field1 = 'id'; value1 = 0;
field2 = 'quiz'; value2=[0 0 0];
vector = struct(field1,value1,field2,value2);
vector(1).id=44;vector(2).id=33;vector(3).id=37;vector(4).id=24;
vector(1).quiz=[7 7.5 8];vector(2).quiz=[5.5 6 6.5];vector(3).quiz=[8 8 8];vector(4).quiz=[6 7 8];
printf("Input: ");
for i=1:4
fprintf('%d ave: %.1f ',vector(i).id,mean(vector(i).quiz));
end
function avg=mean(arr)
avg=(arr(1)+arr(2)+arr(3))/3;
end
function outv = mysort(vec)
for i=1:length(vec)
indlow=i;
for j=i+1:length(vec)
if(mean(vec(j).quiz) < mean(vec(indlow).quiz))
indlow=j;
end
end
temp=vec(i).id;
vec(i).id = vec(indlow).id;
vec(indlow).id=temp;
temp=vec(i).quiz;
vec(i).quiz = vec(indlow).quiz;
vec(indlow).quiz=temp;
end
outv=vec;
end
sortvec=mysort(vector);
printf("Output: ");
for i=1:4
fprintf('%d ave: %.1f ',sortvec(i).id,mean(sortvec(i).quiz));
end
***************************************************************************************************************
Input/Output:
Input:
44 ave: 7.5
33 ave: 6.0
37 ave: 8.0
24 ave: 7.0
Output:
33 ave: 6.0
24 ave: 7.0
44 ave: 7.5
37 ave: 8.0
********************************************************************************
I hope this helps you. Kindly coment if you have any doubts.
If you find my answer helpful,
Kindly rate the answer.
All the best :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.