# [Numpy-discussion] triangular matrix fill

Charles R Harris charlesr.harris@gmail....
Thu May 22 21:07:24 CDT 2008

```On Thu, May 22, 2008 at 7:19 PM, Tom Waite <twaite@berkeley.edu> wrote:

> I have a question on filling a lower triangular matrix using numpy. This
> is essentially having two loops and the inner loop upper limit is the
> outer loop current index. In the inner loop I have a vector being
> multiplied by a constant set in the outer loop. For a matrix N*N in size,
> the C the code is:
>
> for(i = 0; i < N; ++i){
>     for(j = 0; j < i; ++j){
>         Matrix[i*N + j] = V1[i] * V2[j];
>     }
> }
>
>
You can use numpy.outer(V1,V2) and just ignore everything  on and above the
diagonal.

In [1]: x = arange(3)

In [2]: y = arange(3,6)

In [3]: outer(x,y)
Out[3]:
array([[ 0,  0,  0],
[ 3,  4,  5],
[ 6,  8, 10]])

You can mask the upper part if you want:

In [16]: outer(x,y)*fromfunction(lambda i,j: i>j, (3,3))
Out[16]:
array([[0, 0, 0],
[3, 0, 0],
[6, 8, 0]])

Or you could use fromfunction directly.

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20080522/11cb86ac/attachment.html
```