How can I sort data in a loop with an if selection structure?

7 visualizaciones (últimos 30 días)
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 comentarios
Amit Varshney
Amit Varshney el 21 de Oct. de 2014
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..
Michael Toney
Michael Toney el 21 de Oct. de 2014
I got it! I just initiated a while loop with i = 1 and after every if/elseif/else statment with i == 1, i ==2, all the way to i == 9 for the else statement. Then after finding the grades I just did i = i + 1 that way it would go to the next statement. After F2 I just put i = 0 so the loop would terminate.

Iniciar sesión para comentar.

Respuesta aceptada

Mohammad Abouali
Mohammad Abouali el 22 de Oct. de 2014
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.

Más respuestas (0)

Categorías

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

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by