Is it possible to rotate the matrix 45 degrees in the matrix

i.e. so it looks like a diamond. (this is a square matrix) with each row having one more element than the line from the beginning to the middle row, which has the number of elements equal to the sizes of the original matrix, and then goes back again, with each row returning to 1?

+7
matrix matlab orientation
source share
1 answer

Rotation, of course, is impossible, since the "grid" on which the matrix is ​​based is regular.

But I remember what your initial idea was, so the following will help you:

%example data A = magic(5); A = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 

 d = length(A)-1; diamond = zeros(2*d+1); for jj = d:-2:-d ii = (d-jj)/2+1; kk = (d-abs(jj))/2; D{ii} = { [zeros( 1,kk ) A(ii,:) zeros( 1,kk ) ] }; diamond = diamond + diag(D{ii}{1},jj); end 

will return the diamond:

 diamond = 0 0 0 0 17 0 0 0 0 0 0 0 23 0 24 0 0 0 0 0 4 0 5 0 1 0 0 0 10 0 6 0 7 0 8 0 11 0 12 0 13 0 14 0 15 0 18 0 19 0 20 0 16 0 0 0 25 0 21 0 22 0 0 0 0 0 2 0 3 0 0 0 0 0 0 0 9 0 0 0 0 

Now you can search for words or patterns again by row or column by column, just remove the zeros:

Imagine you are extracting one line:

 row = diamond(5,:) 

you can extract nonzero elements with find :

 rowNoZeros = row( find(row) ) rowNoZeros = 11 12 13 14 15 

Not a real diamond, but probably useful:

(The idea is in the comments of @beaker. I will delete this part if he sends it himself.)

 B = spdiags(A) B = 11 10 4 23 17 0 0 0 0 0 18 12 6 5 24 0 0 0 0 0 25 19 13 7 1 0 0 0 0 0 2 21 20 14 8 0 0 0 0 0 9 3 22 16 15 
+10
source share

All Articles