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.

 採用された回答

James Tursa
James Tursa 2017 年 11 月 22 日
編集済み: James Tursa 2017 年 11 月 22 日

0 投票

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 ExchangeMatrix Indexing についてさらに検索

タグ

質問済み:

2017 年 11 月 22 日

編集済み:

2017 年 11 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by