How do I make input/output in a function a vector?
14 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
JESUS DAVID ARIZA ROYETH
2018-5-1
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 个评论
Guillaume
2018-5-1
Now try with
roundGrade([5.5 5.5 5.5])
See discussion in my answer for what is going wrong.
更多回答(1 个)
Guillaume
2018-5-1
编辑:Guillaume
2018-5-1
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!