For a fixed integer n, I have a set of 2(n-1) simultaneous equations as follows.
M(p) = 1+((n-p-1)/n)*M(n-1) + (2/n)*N(p-1) + ((p-1)/n)*M(p-1)
N(p) = 1+((n-p-1)/n)*M(n-1) + (p/n)*N(p-1)
M(1) = 1+((n-2)/n)*M(n-1) + (2/n)*N(0)
N(0) = 1+((n-1)/n)*M(n-1)
M(p) is defined for 1 <= p <= n-1. N(p) is defined for 0 <= p <= n-2. Notice also that p is just a constant integer in every equation so the whole system is linear.
I have been using Maple but I would like to set these up and solve them in python now, maybe using numpy.linalg.solve (or any other better method). I actually only want the value of M(n-1). For example, when n=2 the answer should be M(1) = 4, I believe. This is because the equations become
M(1) = 1+(2/2)*N(0)
N(0) = 1 + (1/2)*M(1)
Therefore
M(1)/2 = 1+1
and so
M(1) = 4.
If I want to plug in n=50, say, how can you set up this system of simultaneous equations in python so that numpy.linalg.solve can solve them?
Update The answers are great but they use dense solvers where the system of equations is sparse. Posted follow up to Using scipy sparse matrices to solve system of equations .
Updated: added implementation using scipy.sparse
This gives the solution in the order
N_max,...,N_0,M_max,...,M_1.The linear system to solve is of the shape
A dot x == const 1-vector.xis the sought after solution vector.Here I ordered the equations such that
xisN_max,...,N_0,M_max,...,M_1.Then I build up the
A-coefficient matrix from 4 block matrices.Here’s a snapshot for the example case

n=50showing how you can derive the coefficient matrix and understand the block structure. The coefficient matrixAis light blue, the constant right side is orange. The sought after solution vectorxis here light green and used to label the columns. The first column show from which of the above given eqs. the row (= eq.) has been derived:As Jaime suggested, multiplying by
nimproves the code. This is not reflected in the spreadsheet above but has been implemented in the code below:Implementation using numpy:
Solution using scipy.sparse:
Example for
n=4:Example for
n=10: