tags:

views:

263

answers:

3

Using NumPy, a matrix A has n rows and m columns, and I want add a guard ring to matrix A. That guard ring is all zero.

What should I do? Use Reshape? But the element is not enough to make a n+1 m+1 matrix.

Or etc.?

Thanks in advance

I mean an extra ring of cells that always contain 0 surround matrix A.Basically there is a Matrix B has n+2rows m+2columns where the first row and columns and the last row and columns are all zero,and the rest of it are same as matrix A.
A: 

What do you mean by guard ring?

fivebells
many apologies,I mean an extra ring of cells that always contain 0 surround matrix A.Basically there is a Matrix B has n+1rows m+1columns where the first row and columns and the last row and columns are all zero,and the rest of it are same as matrix A.
NONEenglisher
You mean n+2 rows and m+2 columns?
kigurai
...oh,yeah.......sorry..my mistake..
NONEenglisher
+2  A: 

Following up on your comment:

>>> import numpy
>>> a = numpy.array(range(9)).reshape((3,3))
>>> b = numpy.zeros(tuple(s+2 for s in a.shape), a.dtype)
>>> b[tuple(slice(1,-1) for s in a.shape)] = a
>>> b
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 2, 0],
       [0, 3, 4, 5, 0],
       [0, 6, 7, 8, 0],
       [0, 0, 0, 0, 0]])
fivebells
Wanted to mention that at least with the version of NumPy (1.2.0 release) and Python (2.5.2) I have, the conversion to tuple is unnecessary and omitting it appeared to save time in my own limited testing. I forgot you could use slices like this!! Python is like the Feng Shui of programming.
Chris Cameron
And by 'omitting' I mean using [] instead of tuple(). Oops :)
Chris Cameron
A: 

This is a less general but easier to understand version of Alex's answer:

>>> a = numpy.array(range(9)).reshape((3,3))
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b = numpy.zeros(a.shape + numpy.array(2), a.dtype)
>>> b
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> b[1:-1,1:-1] = a
>>> b
array([[0, 0, 0, 0, 0],
       [0, 0, 1, 2, 0],
       [0, 3, 4, 5, 0],
       [0, 6, 7, 8, 0],
       [0, 0, 0, 0, 0]])
J.F. Sebastian