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.

 Réponse acceptée

James Tursa
James Tursa le 22 Nov 2017
Modifié(e) : James Tursa le 22 Nov 2017
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, : );

Plus de réponses (0)

Catégories

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by