How to index and replace
18 次查看(过去 30 天)
显示 更早的评论
Hello,
I am trying to learn MATLAB and decided to use the MIT course to look at the slides and I figure the homework would be challenging so I decided to do that as well. I am stuck on problem 9.G.iii. Can someone please assist me.
Here is my code
clear all, close all, clc
%b
load classGrades
%c
namesAndGrades
%d
grades = namesAndGrades(:,2:end)
%e
meanGrades = nanmean(grades(:,1))
for i = 1:7
meanGrades(i,:) = nanmean(grades(:,i))
end
[gradesRows, gradesCol] = size(grades)
%f
for i = 1:15
meanMatrix(i,:) = meanGrades
end
curvedGrades = 3.5*(grades./meanMatrix)
checkCurvedGrades = nanmean(curvedGrades);
%f.iv
curvedGrades5 = find(curvedGrades > 5)
for i = curvedGrades5
curvedGrades(i) = 5
end
checkCurve = find(curvedGrades == 5)
tf = isequal(curvedGrades5,checkCurve)
%g
totalGrade = nanmean(curvedGrades')
totalGrade = ceil(totalGrade)
letters = ['F','D','C','B','A'];
findF = find(totalGrade ==1);
findD = find(totalGrade ==2);
findC = find(totalGrade ==3);
findB = find(totalGrade ==4);
findA = find(totalGrade ==5);
0 个评论
采纳的回答
Stephen23
2017-1-12
编辑:Stephen23
2017-1-12
totalGrade is already the index (values from one to five) that can be used directly into letters, therefore you do not need find or the equivalence operation, and I also simplified your concatenating characters into one string:
letters = 'FDCBA';
letterGrades = letters(totalGrades)
This simply follows exactly what the instructions state: "make the final letter grades ... by using totalGrades... to index into letters". The instructions do not tell you to use find, or equivalence operators.
In fact all of your code uses unnecessary find operations, and very inefficient loops. Loops are not the point of this homework. The very first line states that the point is to think about using MATLAB "in terms of matrices and vectors because that is how MATLAB organizes data". You are still thinking in terms of loops, which are slow, ugly, and are definitely not thinking about data in terms of matrices and vectors.
For example, this slow find and ugly loop:
curvedGrades5 = find(curvedGrades > 5)
for i = curvedGrades5
curvedGrades(i) = 5;
end
should be just one line using logical indexing:
curvedGrades(curvedGrades>5) = 5;
If you want to learn how to use MATLAB efficiently then you need to revise your work, and especially learn about logical indexing.
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!