How do I make input/output in a function a vector?
14 views (last 30 days)
Show older comments
Clara Kühnel
on 1 May 2018
Commented: Guillaume
on 1 May 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 Comments
Accepted Answer
JESUS DAVID ARIZA ROYETH
on 1 May 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 Comments
Guillaume
on 1 May 2018
Now try with
roundGrade([5.5 5.5 5.5])
See discussion in my answer for what is going wrong.
More Answers (1)
Guillaume
on 1 May 2018
Edited: Guillaume
on 1 May 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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!