Effacer les filtres
Effacer les filtres

How to round elements in a vector to pre-defined intervals

3 vues (au cours des 30 derniers jours)
Sandie Nhatien Vu
Sandie Nhatien Vu le 12 Août 2016
Commenté : Sandie Nhatien Vu le 12 Août 2016
function gradesRounded = roundGrade(grades)
%roundGrade rounds off each element in a vector to the nearest grade in
%the 7-step scale
%
%Input grades: a vector, each element is a number between -3 and 12
%Output gradesRounded: a vector, each element is a number on the 7-step
%scale
% Start empty vector
gradesRounded = [];
%Rounded grades
for i=1:length(grades)
if grades(i) < -1.5
gradesRounded = -3;
elseif grades(i) >= -1.5 && grades(i) < 1
gradesRounded = 0;
elseif grades(i) >= 1 && grades(i) < 3
gradesRounded(i) = 2;
elseif grades(i) >= 3 && grades(i) < 5.5
gradesRounded(i) = 4;
elseif grades(i) >= 5.5 && grades(i) < 8.5
gradesRounded(i) = 7;
elseif grades(i) >= 8.5 && grades(i) < 11
gradesRounded(i) = 10;
elseif grades(i) >= 11
gradesRounded(i) = 12;
end
end
So far i have this code.. I have to make a function that takes in a vector with numbers between -3 and 12 and as output it should come out with a vector, where all elements are rounded to the nearest number in a scale that goes: 12 10 7 4 2 00 -3
But when i run the code, l only get one value, not a vector.. I know that the commando l can use is interp1, but isn't there a way l can solve this by using loops?
  1 commentaire
Adam
Adam le 12 Août 2016
Your first two case just write to a scalar so if any of those gets hit it will overwrite the vector you are creating in the rest of the cases.

Connectez-vous pour commenter.

Réponse acceptée

the cyclist
the cyclist le 12 Août 2016
Putting Adam's response as an answer instead of a comment, and explaining it in a bit more detail:
In the first and second part of the "if" statement, you have this bit of code
gradesRounded = -3;
instead of this bit of code:
gradesRounded(i) = -3;
which means that you are over-writing your entire vector with a single number, instead of writing to each element of the vector.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by