Well, for my class of numerical methods, I have the following question:
Write a Python function to solve Ax = b by inverse substitution, where A is the upper triangular nonsingular matrix. The MATLAB code for this is on page 190, which you can use as a pseudo-code guide if you want. The function should take A and b as input and return x. Your function should not check that A is non-singular. That is, suppose that only non-singular A. will be passed to your function.
The MATLAB code to which it refers is:
x(n) = c(u)/U(n,n) for i = n-1 : -1 : 1 x(i) = c(i); for j = i+1 : nx(i) = x(i) - U(i,j)*x(j); end x(i) = x(i)/U(i,i); end
My Python code, which I wrote using the MATLAB code snippet, has an upper triangular test matrix (not sure if it is non-singular!). How can I check the singularity?):
from scipy import mat c=[3,2,1] U=([[6,5,1],[0,1,7],[0,0,2]]) a=0 x=[] while a<3: x.append(1) a=a+1 n=3 i=n-1 x[n-1]=c[n-1]/U[n-1][n-1] while i>1: x[i]=c[i] j=i+1 while j<n-1: x[i]=x[i]-U[i][j]*x[j]; x[i]=x[i]/U[i][i] i=i-1 print mat(x)
The answer I get is [[1 1 0]] for x. I'm not sure I'm doing it right. I guess this is wrong and cannot figure out what to do next. Any clues?
source share