Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %Constants
- y0 = 0;
- y1 = 1;
- n = 2:2:10;
- x_range = 0:1/1000:1;
- %Creates a vector y_correct with the values for the analytical solution,
- %using dx = 1/1000
- for j = length(x_range)
- y_correct = ones(1, length(x_range));
- y_correct(j) = 1.3888*exp(x_range(j)) + 0.6112*exp(-x_range(j)) - x_range(j)^2 -2;
- end
- for i = n
- BVPsolver(i);
- end
- plot(x_range, y_correct)
- legend('n=2', 'n=4', 'n=6', 'n=8', 'n=10', 'Analytical')
- xlabel('x')
- ylabel('y(x)')
- title('BVP Problem Solution')
- function BVPsolver(n)
- %Creating constants for current value of n
- dx = 1/n;
- range = 0:dx:1;
- %Creating matrix b out of a ones array with height of n-1, width 1
- b = ones(n-1, 1);
- %Multiplying all ones in b by dx^4
- b = b.*(dx^4);
- %The pattern found in b, for y(nΔx), b = n^2*Δx^4, so we're just
- %multiplying by n^2 here
- for j = 1:(n-1)
- b(j) = b(j)*j^2;
- end
- %Subtracting y1 from the last value of b
- b(end) = b(end)-1;
- %Constants for the diagonals of matrix A
- k1 = 1;
- k2 = -2-dx^2;
- k3 = 1;
- %Creating a matrix with diagonals of the constants above, and all other
- %values = 0
- A = diag(ones(1, n-2).*k1, 1) + diag(ones(1, n-1).*k2) + diag(ones(1, n-2).*k1, -1);
- y = [0;mldivide(A, b);1];
- plot(range, y, 'DisplayName',strcat('n=',num2str(n)))
- grid on
- hold on
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement