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.

 Akzeptierte Antwort

James Tursa
James Tursa am 22 Nov. 2017
Bearbeitet: James Tursa am 22 Nov. 2017

0 Stimmen

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, : );

Weitere Antworten (0)

Kategorien

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by