Matlab grader discretization help
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello,
I am stuck on a Matlab grader problem about discretization. I am wondering if anyone is able to help me figure out what is wrong with my code/what I need to change or add? The asignment is attached in a file called grader asignment. My code and the asignment code is below. I wrote the function, the main program is given.
N = 10;
q = @(x) x;
k = 4;
Tl = 1;
Tr = 2;
[A,HL] = diskretisering_temperatur(N,q,k,Tl,Tr);
% solve the problem
sol = A\HL;
% plot solution with boundary values
h = 1/N;
x = [h:h:1-h]';
figure
plot([0; x; 1],[Tl; sol; Tr])
function [A,HL] = diskretisering_temperatur(N,q,k,Tl,Tr)
h = 1/N;
x = [h:h:1-h]';
% Create the coefficient for the finite difference
coefficient = k / h^2;
% Initialize the right-hand side vector HL
HL = zeros(N-1, 1);
% Apply the heat source function q(x) to the right-hand side vector HL
for i = 1:N-1
HL(i) = q(x(i));
end
% Apply the boundary conditions to the system
HL(1) = HL(1) - Tl * coefficient; % Apply the left boundary condition
HL(N-1) = HL(N-1) - Tr * coefficient; % Apply the right boundary condition
% Initialize the diagonals of the system matrix A
main_diagonal = -2 * coefficient * ones(N-1, 1);
off_diagonal = coefficient * ones(N-2, 1);
% Construct the sparse matrix A using the diagonals
A = spdiags([off_diagonal main_diagonal off_diagonal], -1:1, N-1, N-1);
end
댓글 수: 0
답변 (1개)
Torsten
2023년 12월 1일
Use
off_diagonal = coefficient * ones(N-1, 1);
instead of
off_diagonal = coefficient * ones(N-2, 1);
See the example "Create Tridiagonal Matrix" under
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!