what is the problem of this function code?

function sectionGrades = extractSection(grades, sectionNumber)
for i = 1 : 7
if grades(i,2) ~= sectionNumber
grades(i,:) = [];
else
end
end
sectionGrades = grades;
end
it keeps saying Error in extractSection (line 6) if grades(i,2) == sectionNumber
what is wrong with this?
I saved this file as extractSection.m
and 'grades' is a matrix that i downloaded.

 采纳的回答

The reason you are getting the error is because you change the size of the grades variable within the loop, so the last index(es) of the loop are not valid if you have deleted anything. You can fix that a few different ways. One is to run your loop in reverse so that the indexes are always valid. E.g.,
for i = 7 : -1 : 1
Another way is to avoid the loop entirely and just use logical indexing to get the result directly. E.g.,
sectionGrades = grades( grades(:,2)==sectionNumber, : );

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by