matrix manupulation and reading diagonally

Hello Team,
i have a matrix
Matrix_test = [13,10,5,2;7,14,11,6;3,8,15,12;1,4,9,16];
I want to read the matrix in the order mentioned in the matrix.
Starting from left bottom (1), then right top (2) and then again 2nd diagonal from left (3,4) and then 2nd right diagonal (5,6) and so on and so forth.
Please support in resolving it.
Edit : i there any way to create this kind of matrix for any n-by-n matrix automatically. i have created this Matrix_test manually but if i want 8x8 matrix in similar pattern . How to create it through generic code.
Thanks in advance.

 채택된 답변

Stephan
Stephan 2020년 12월 8일

0 개 추천

This function may help:
M = [13,10,5,2;7,14,11,6;3,8,15,12;1,4,9,16]
MyResult = readDiag(M)
function R = readDiag(M)
R = cell(2,numel(diag(M)));
for k = 1:numel(diag(M))-1
R{1,k} = diag(M,-numel(diag(M))+k);
R{2,k} = diag(M,numel(diag(M))-k);
end
R = reshape(R,[],1);
R = [R; {diag(M)}];
R = cell2mat(R);
end
result is:
M =
13 10 5 2
7 14 11 6
3 8 15 12
1 4 9 16
MyResult =
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

댓글 수: 2

NIKHIL
NIKHIL 2020년 12월 11일
Thank your for your solution.
NIKHIL
NIKHIL 2020년 12월 11일
Hello Stephen, I have edited one additional question related to this query. How to create similar type of Matrix_test automatically with some code. can you please revert back to this query also ?

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

추가 답변 (1개)

Bruno Luong
Bruno Luong 2020년 12월 8일
편집: Bruno Luong 2020년 12월 8일

0 개 추천

Matrix_test = [13,10,5,2;7,14,11,6;3,8,15,12;1,4,9,16]
[m,n]=size(Matrix_test);
[i,j]=ndgrid(1:m,1:n);
jmi = j(:)-i(:);
[~,is]=sortrows([-abs(jmi) jmi]);
Matrix_test(is)

댓글 수: 4

NIKHIL
NIKHIL 2020년 12월 11일
Thank you for your response. It is working well.
NIKHIL
NIKHIL 2020년 12월 11일
Hello Bruno, I have edited one additional question related to this query. How to create similar type of Matrix_test automatically with some code. can you please revert back to this query also ?
Create matrix with dimension m x n.
m=8; n=8;
[i,j]=ndgrid(1:m,1:n);
jmi = j(:)-i(:);
[~,is]=sortrows([-abs(jmi) jmi]);
M=zeros(m,n);
M(is)=1:m*n
NIKHIL
NIKHIL 2020년 12월 11일
Thank you so much Bruno for quick response.
It is working really good

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

질문:

2020년 12월 8일

댓글:

2020년 12월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by