Sorting a matrix with conditions to a new vector column
2 views (last 30 days)
Show older comments
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 Comment
Ameer Hamza
on 8 May 2020
Can you show an example of output? What do you expect the values of A, B, C, ... after running the code.
Accepted Answer
Ameer Hamza
on 8 May 2020
Edited: Ameer Hamza
on 8 May 2020
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 Comments
Ameer Hamza
on 8 May 2020
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
on 8 May 2020
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.
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!