[wplug] Python question

Mike Sussman sussmanm at math.pitt.edu
Thu Dec 12 16:10:09 EST 2013


As part of a course, I want to describe how to write a simple finite
element analysis program using Python.  Since this is a demonstration, I
want the code to be as simple as possible.  I have run into a place where I
can write the code in a loop but I can't seem to write it using array
syntax.

A basic operation is to construct a large matrix M (think 10000 X 10000) by
calculating many (think 5000) small matrices m (think 20 X 20) and then
adding them into M in way described by an index array n[20] whose values
are the places in M where things go.  In C the code would look like:
for(i=0;i<20;i++){for(j=0;j<20;j++){M[n[i]][n[j]]=m[i][j];}}
In Fortran or Matlab, array notation would allow the simpler code:
M(n,n)=m
or, including the colons
M(n(:),n(:))=m(:,:)

In Python, using numpy arrays or numpy matrices, the array syntax that
works for Matlab doesn't work.  You get an error "ValueError: array is not
broadcastable to correct shape".  You can replace either one of the colons
with a loop and it will work correctly, but the result is ugly, hard to
understand, and even harder to teach.  You can also play tricks with
reshape, but that is even uglier.

Is there some syntax I am missing?  Is there a clean way to copy a small 2D
array into a large 2D array without looping?

Thanks,
Mike Sussman


More information about the wplug mailing list