How can I sort data in a loop with an if selection structure?
7 次查看(过去 30 天)
显示 更早的评论
Say if I have a vector of numbers grades = [84;62;91;85;73;69;44;90;82] and I want to sort them like grades, A being 90-100, B being 80-89, C being 70-79, D being 60-69, and F below 60. I want to use a loop with an if selection structure to sort them. But when I run my code only my F values show up with a column vector of zeros and 1's being in place of the values that are true for the F grades. Any suggestions on how to correctly do this?
4 个评论
Amit Varshney
2014-10-21
You do need the 'if' and 'elseif' statements. Try the following
A2 = grades(find(grades >= 93))
A_m2 = grades(find(grades >= 90 & grades < 93))
ans so on..
采纳的回答
Mohammad Abouali
2014-10-22
Another way of coding without all these if then classes is this:
% Generating some random grades
Grades_Numeric=randi(100,[10,1]);
levels=[60,70,77,80,83,87,90,93,97];
GradesClasses={'F';'D';'C';'C+';'B-';'B';'B+';'A-';'A';'A+'};
% now getting each grade falls in what category
Grades_Mask=imquantize(Grades_Numeric,levels);
[Grades_Mask Grades_Numeric]
ans =
2 66
1 50
4 78
3 72
8 91
7 90
1 34
2 70
1 20
1 4
%retrieving the categorial grades.
GradesClasses(Grades_Mask)
ans =
'D'
'F'
'C+'
'C'
'A-'
'B+'
'F'
'D'
'F'
'F'
The good thing about this approach is that if you want to change your levels and classes you don't need to write any code, (may be not in this case) but in cases that these classes and levels are not decided they can be easily passed as an input to a function.
0 个评论
更多回答(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!