Sorting a matrix with conditions to a new vector column
조회 수: 2 (최근 30일)
이전 댓글 표시
If I have a matrix
A = [2 5 6 0 4 9 10 3 2 7 5];
and I'd like to sort it in a for loop with a condition such that, for example, 9 or above gets an A, 7 or below gets a B, 5 or below gets a C, and 3 or below gets an F. How can I write a for loop that would give me a column vector with the classifications (A, B, C...)?
I've tried writing a loop with an index set to the length of A, but I'm not sure what to do about it.
Any help is appreciated
댓글 수: 1
Ameer Hamza
2020년 5월 8일
Can you show an example of output? What do you expect the values of A, B, C, ... after running the code.
채택된 답변
Ameer Hamza
2020년 5월 8일
편집: Ameer Hamza
2020년 5월 8일
Try this
A = [2 5 6 0 4 9 10 3 2 7 5];
edges = [0 3 5 7 9 inf];
grades = {'F', 'D', 'C', 'B', 'A'};
idx = discretize(A, edges);
B = grades(idx);
[A, idx] = sort(A, 'descend');
B = B(idx);
t = table(A.', B.', 'VariableNames', {'Grades', 'Grade Letter'})
Result
t =
11×2 table
Grades Grade Letter
______ ____________
10 {'A'}
9 {'A'}
7 {'B'}
6 {'C'}
5 {'C'}
5 {'C'}
4 {'D'}
3 {'D'}
2 {'F'}
2 {'F'}
0 {'F'}
댓글 수: 4
Ameer Hamza
2020년 5월 8일
If sorting is not important, then try this
A = [5 ;
7 ;
3 ;
6.1 ;
5 ;
4 ;
3 ;
2 ;
1;
7];
edges = [0 4 5 6 7 inf];
grades = {'5th', '4th', '3rd', '2nd', '1st'}.';
idx = discretize(A, edges);
B = grades(idx);
t = table(A, B, 'VariableNames', {'Grades', 'Grade Letter'})
Result
t =
10×2 table
Grades Grade Letter
______ ____________
5 {'3rd'}
7 {'1st'}
3 {'5th'}
6.1 {'2nd'}
5 {'3rd'}
4 {'4th'}
3 {'5th'}
2 {'5th'}
1 {'5th'}
7 {'1st'}
Ameer Hamza
2020년 5월 8일
The vector
edges = [0 4 5 6 7 inf];
have 5 intervals. Therefore the vector grades must also have 5 values. If you want to change the number of elements in grades, then you should also change edges accordingly.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!