필터 지우기
필터 지우기

Matlab grader discretization help

조회 수: 3 (최근 30일)
Alexander
Alexander 2023년 12월 1일
답변: Torsten 2023년 12월 1일
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

답변 (1개)

Torsten
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by