How can I sort data in a loop with an if selection structure?
10 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Michael Toney
il 21 Ott 2014
Risposto: Mohammad Abouali
il 22 Ott 2014
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 Commenti
Amit Varshney
il 21 Ott 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..
Risposta accettata
Mohammad Abouali
il 22 Ott 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.
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!