How do I make input/output in a function a vector?
14 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Clara Kühnel
il 1 Mag 2018
Commentato: Guillaume
il 1 Mag 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
0 Commenti
Risposta accettata
JESUS DAVID ARIZA ROYETH
il 1 Mag 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 Commenti
Guillaume
il 1 Mag 2018
Now try with
roundGrade([5.5 5.5 5.5])
See discussion in my answer for what is going wrong.
Più risposte (1)
Guillaume
il 1 Mag 2018
Modificato: Guillaume
il 1 Mag 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.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!