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

14 visualizaciones (últimos 30 días)
Clara Kühnel
Clara Kühnel el 1 de Mayo de 2018
Comentada: Guillaume el 1 de Mayo de 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

Respuesta aceptada

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH el 1 de Mayo de 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 comentarios
Clara Kühnel
Clara Kühnel el 1 de Mayo de 2018
Ahh, I called it by the second one - I see my mistake. Thank you very much!
Guillaume
Guillaume el 1 de Mayo de 2018
Now try with
roundGrade([5.5 5.5 5.5])
See discussion in my answer for what is going wrong.

Iniciar sesión para comentar.

Más respuestas (1)

Guillaume
Guillaume el 1 de Mayo de 2018
Editada: Guillaume el 1 de Mayo de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by