Matlab grader discretization help
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Torsten
am 1 Dez. 2023
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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!