Matlab grader discretization help
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Torsten
le 1 Déc 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 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!