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

조회 수: 7 (최근 30일)
Michael Toney
Michael Toney 2014년 10월 21일
답변: Mohammad Abouali 2014년 10월 22일
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
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..
Michael Toney
Michael Toney 2014년 10월 21일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Mohammad Abouali
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개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by