Please change this code into Python code. function A = StiffnessAssembler1D(x,a,kappa) n = length(x)-1; A = sparse(n+1,n+1); %A = zeros(n+1,n+1); for i = 1:n h = x(i+1) - x(i); xmid = (x(i+1) + x(i))/2; amid = a(xmid); A(i,i) = A(i,i) + amid/h; A(i,i+1) = A(i,i+1) - amid/h; A(i+1,i) = A(i+1,i) - amid/h; A(i+1,i+1) = A(i+1,i+1) + amid/h; end A(1,1) = A(1,1) + kappa(1); A(n+1,n+1) = A(n+1,n+1) + kappa(2); end function b = SourceAssembler1D(x,f,kappa,g) n = length(x)-1; b = sparse(n+1,1); %b = zeros(n+1,1); for i = 1:n h = x(i+1) - x(i); b(i) = b(i) + f(x(i))*h/2; b(i+1) = b(i+1) + f(x(i+1))*h/2; end b(1) = b(1) + kappa(1)*g(1); b(end) = b(end) + kappa(2)*g(2); end h = 0.1; x = 2:h:8; kappa = [1.e+6 0]; g = [-1 0]; Conductivity = @(x) 0.1*(5 - 0.6*x); Source = @(x) 0.03*(x-6)^4; A = StiffnessAssembler1D(x, Conductivity, kappa); b = SourceAssembler1D(x, Source, kappa, g); u = A\b; plot(x,u)
Please change this code into Python code.
function A = StiffnessAssembler1D(x,a,kappa)
n = length(x)-1;
A = sparse(n+1,n+1); %A = zeros(n+1,n+1);
for i = 1:n
h = x(i+1) - x(i);
xmid = (x(i+1) + x(i))/2;
amid = a(xmid);
A(i,i) = A(i,i) + amid/h;
A(i,i+1) = A(i,i+1) - amid/h;
A(i+1,i) = A(i+1,i) - amid/h;
A(i+1,i+1) = A(i+1,i+1) + amid/h;
end
A(1,1) = A(1,1) + kappa(1);
A(n+1,n+1) = A(n+1,n+1) + kappa(2);
end
function b = SourceAssembler1D(x,f,kappa,g)
n = length(x)-1;
b = sparse(n+1,1); %b = zeros(n+1,1);
for i = 1:n
h = x(i+1) - x(i);
b(i) = b(i) + f(x(i))*h/2;
b(i+1) = b(i+1) + f(x(i+1))*h/2;
end
b(1) = b(1) + kappa(1)*g(1);
b(end) = b(end) + kappa(2)*g(2);
end
h = 0.1;
x = 2:h:8;
kappa = [1.e+6 0];
g = [-1 0];
Conductivity = @(x) 0.1*(5 - 0.6*x);
Source = @(x) 0.03*(x-6)^4;
A = StiffnessAssembler1D(x, Conductivity, kappa);
b = SourceAssembler1D(x, Source, kappa, g);
u = A\b;
plot(x,u);
Step by step
Solved in 4 steps with 3 images