How do I make input/output in a function a vector?

14 vues (au cours des 30 derniers jours)
Clara Kühnel
Clara Kühnel le 1 Mai 2018
Commenté : Guillaume le 1 Mai 2018
I'm trying to make a grade-rounding function. How do I make sure my function works on each value I type in at once. E.g. the inputvector [7.2,10.3] should give me the outputvector [7,10]
function gradesRounded = roundGrade(grades)
if grades <= -2
gradesRounded=-3;
elseif grades <1 && grades > -2
gradesRounded=00;
elseif grades < 3 && grades >=1
gradesRounded=02;
elseif grades < 5.5 && grades >= 3
gradesRounded=4;
elseif grades < 8.5 && grades > 5.5
gradesRounded=7;
elseif grades >= 8.5 && grades < 11
gradesRounded=10;
elseif grades >= 11
gradesRounded=12;
end
end

Réponse acceptée

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH le 1 Mai 2018
one cycle is missing
function gradesRounded = roundGrade(grades)
gradesRounded=grades;
for k=1:numel(grades)
if grades(k) <= -2
gradesRounded(k)=-3;
elseif grades(k) <1 && grades(k) > -2
gradesRounded(k)=00;
elseif grades(k) < 3 && grades(k) >=1
gradesRounded(k)=02;
elseif grades(k) < 5.5 && grades(k) >= 3
gradesRounded(k)=4;
elseif grades(k) < 8.5 && grades(k) > 5.5
gradesRounded(k)=7;
elseif grades(k) >= 8.5 && grades(k) < 11
gradesRounded(k)=10;
elseif grades(k) >= 11
gradesRounded(k)=12;
end
end
end
  4 commentaires
Clara Kühnel
Clara Kühnel le 1 Mai 2018
Ahh, I called it by the second one - I see my mistake. Thank you very much!
Guillaume
Guillaume le 1 Mai 2018
Now try with
roundGrade([5.5 5.5 5.5])
See discussion in my answer for what is going wrong.

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 1 Mai 2018
Modifié(e) : Guillaume le 1 Mai 2018
You could wrap your existing near endless list of if ... elseif into a for loop... (see answer by Jesus) ...
Or you could use matlab the way it's meant, with the discretize function.
function gradesRounded = roundGrade(grades)
edge_grade_pair= [-Inf -3; -2 0; 1 2; 3 4; 5.5 7; 8.5 10; 11 12; Inf NaN];
gradesRounded = edge_grade_pair(discretize(grades, edge_grade_pair(:, 1)), 2);
end
A lot more compact! And it's trivial to add more edges if needed. Just two more values in the matrix.
One minor difference is that the above results in 0 for exact -2 while your code results in -3 but considering that your code is not consistent with which edge is included in which bracket (for example your code won't return anything for exact 5.5 since it's not included in any bracket), I assume you've got it wrong.

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