If you have the 3*3 matrix
C = [3 4 5
6 7 9
1 5 8]
and you want to change it to the 3*1 matrix
C = [345
679
158]
so that you can for example sort it in descending order of the rows, how would you do this? Thank you.

 채택된 답변

Chris
Chris 2021년 10월 31일
편집: Chris 2021년 10월 31일
Edit: Use Star Strider's answer. It's faster.
C = [3 4 5
6 7 9
1 5 8]
C = 3×3
3 4 5 6 7 9 1 5 8
C = double(string(C).join(''))
C = 3×1
345 679 158

댓글 수: 3

Breaking it down:
C = [3 4 5
6 7 9
1 5 8] % The matrix
C = 3×3
3 4 5 6 7 9 1 5 8
string(C) % String arrays are nice to work with
ans = 3×3 string array
"3" "4" "5" "6" "7" "9" "1" "5" "8"
string(C).join('') % Mush the strings together with no delimiter between
ans = 3×1 string array
"345" "679" "158"
C = double(string(C).join('')) % Cast the output back into a double array
C = 3×1
345 679 158
Another approach —
C = [3 4 5
6 7 9
1 5 8]
C = 3×3
3 4 5 6 7 9 1 5 8
C*10.^[2;1;0]
ans = 3×1
345 679 158
Just thought I’d add that for fun!
.
Interesting. This was probably the most obvious method before strings? Easily generalized for an array of single-digit integers:
C*10.^[size(C,2)-1:-1:0]'

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

질문:

2021년 10월 31일

편집:

2021년 10월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by