Borrar filtros
Borrar filtros

Matlab grader discretization help

3 visualizaciones (últimos 30 días)
Alexander
Alexander el 1 de Dic. de 2023
Respondida: Torsten el 1 de Dic. de 2023
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);
Error using horzcat
Dimensions of arrays being concatenated are not consistent.

Error in solution>diskretisering_temperatur (line 44)
A = spdiags([off_diagonal main_diagonal off_diagonal], -1:1, N-1, N-1);
% 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

Respuestas (1)

Torsten
Torsten el 1 de Dic. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by