How can I re-write this code to fit any size matrix? Help!

1 次查看(过去 30 天)
I have written a code to calculate the end grade(sum) while dropping the lowest grade value between a specific number of columns in a matrix. This code only works for a 10*5 matrix I need to create a code that works for any size matrix. My current code will be written below. Thanks in advance.
function updatedGrades = computeTotal(sectionGrades) % Modify xxx,yyy to variable names of your choice. % Comment what this function is about here.
% Put the body of your function here. Don't forget to assign output variable! e.g. xxx = something
grades2=sectionGrades([1], [3:8]) grades3=sectionGrades([2], [3:8]) grades4=sectionGrades([3], [3:8]) grades5=sectionGrades([4], [3:8])
grades2a=sum(grades2)-min(grades2) grades3b=sum(grades3)-min(grades3) grades4c=sum(grades4)-min(grades4) grades5d=sum(grades5)-min(grades5)
grades23=grades2a+sum(sectionGrades([1], [9:10])) grades34=grades3b+sum(sectionGrades([2], [9:10])) grades45=grades4c+sum(sectionGrades([3], [9:10])) grades56=grades5d+sum(sectionGrades([4], [9:10]))
finalGrades=[grades23;grades34;grades45;grades56]
sectionGrades([1:4],[11])=finalGrades
updatedGrades=sectionGrades

采纳的回答

KL
KL 2017-11-25
编辑:KL 2017-11-25
You're complicating a simple one line calculation way too much. Here's how to do it effectively,
sectionGrades(:,end+1) = sum(sectionGrades(:,3:8),2)-min(sectionGrades(:,3:8),1,2)...
+sum(sectionGrades(:,9:10),2);
Now it does't matter how many rows you add to the matrix, the last column should be calculated accordingly.
  3 个评论
Reni Llupa
Reni Llupa 2017-11-25
also, the final matrix has to be assigned to 'updatedGrades'
KL
KL 2017-11-25
Sorry, I missed one argument in min command, fixed it now and it should work. If you want to assign it to 'updatedGrades', simply assign it!

请先登录,再进行评论。

更多回答(0 个)

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by