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

조회 수: 1 (최근 30일)
Reni Llupa
Reni Llupa 2017년 11월 25일
편집: KL 2017년 11월 25일
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