matlab/numpy submatrix contour

72 views Asked by At

I'm looking for a way to get the contour of a matlab/numpy submatrix. For example, if I have :

A=
[x,x,x,x,x,x,x]
[x,x,x,x,x,x,x]
[x,1,2,3,4,x,x]
[x,5,x,x,6,x,x]
[x,7,8,9,10,x,x]
[x,x,x,x,x,x,x]

Is there a way to get [1,2,3,4,6,10,9,8,7,5] faster (ie more readable) than slicing every edge and then concatenating them ?

EDIT : The problem is that slicing with numpy is bothersome. For example, let's say I have i0,i1,j0,j1 to identify the submatrix :

I wanted to do : np._r[A[i0,j0:j1+1],A[i0:i1+1,j1],A[i1,j1:j0-1:-1],A[i1:i0-1:-1,j0]]

But [j1:j0-1:-1] does not work if j0==0, as [j1:-1:-1] returns an empty slice...

EDIT 2 : The following slice seems to work, I'm not sure it's really good, but I have not manage to do better.

np._r[A[i0,j0:j1+1],A[i0+1:i1+1,j1],(A[i1,j0+1:j1+1])[::-1],(A[i0+1:i1+1,j0])[::-1]]

Still thanks to all those who answered, if you found a better way, do not hesitate to post.

2

There are 2 answers

1
Peter On
rows = [2,2,2,2,3,4,4,4,4,3]
cols = [1,2,3,4,4,4,3,2,1,1]
A[rows, cols]

Should return [1,2,3,4,5,6,7,8,9,a] in your case.

0
Kiko On

I think this is a good solution:

contour = [A(3,2:5) A(4,5) A(5,5:-1:2) A(4,2)];

here the value of contour will be your array [1,2,3,4,5,6,7,8,9,a]