Need help turning this code into Python Code please. function A = StiffnessAssembler1D(x) n = length(x)-1; A = sparse(n-1,n-1); for i = 1:n-2 h = x(i+2) - x(i+1); A(i,i) = A(i,i) + 1/h; A(i,i+1) =...


Need help turning this code into Python Code please.



function A = StiffnessAssembler1D(x)


n = length(x)-1;


A = sparse(n-1,n-1);


for i = 1:n-2


h = x(i+2) - x(i+1);


A(i,i) = A(i,i) + 1/h;


A(i,i+1) = A(i,i+1) - 1/h;


A(i+1,i) = A(i+1,i) - 1/h;


A(i+1,i+1) = A(i+1,i+1) + 1/h;


end


A(1,1) = A(1,1) + 1/h;


A(n-1,n-1) = A(n-1,n-1) + 1/h;


end



function b = SourceAssembler1D(x,f,g)


n = length(x)-1;


b = sparse(n-1,1);


for i = 1:n-2


h = x(i+2) - x(i+1);


b(i) = b(i) + f(x(i+1))*h/2;


b(i+1) = b(i+1) + f(x(i+2))*h/2;


end


b(1) = b(1) + g(1)/h +f(x(2))*h/2;


b(n-1) = b(n-1) + g(2)/h +f(x(n))*h/2;


end



u_exact = @(x) (exp(x).*cos(x)/2)';


aa=0:0.01:2;


plot(aa,u_exact(aa),'r--')


hold on;


h = 0.5;


x = 0:h:2;


g = [0.5 exp(2)*cos(2)/2];


A = StiffnessAssembler1D(x);


f = @(x) exp(x)*sin(x);


b = SourceAssembler1D(x, f, g);


u_freedom = A\b;


u = [g(1);u_freedom;g(2)];


plot(x,u);


legend('Exact Solution','Numerical Solution');


hold off




Jun 07, 2022
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here