Creating a Tridiagonal matrix in matlab

$\begingroup$

How can I create a tridiagonal matrix that I can use for Crout factorization? And, I don't have any codes on how to create one since I am new to matlab.

enter image description here

Ok, please help me understand what does the sentence "The program should output the $\infty$ norm of the residual of your computed solution and the number of iterations used" mean in this case? I am all confused figuring this out.

$\endgroup$

4 Answers

$\begingroup$
>> n = 10;
>> full(gallery('tridiag',n,-1,2,-1))
ans = 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2 -1 0 0 0 0 0 0 0 0 -1 2

Crout:

% Source:
% MATLAB implementation of Crout reduction algorithm (p. 140 of your book)
function [L,U] = crout(A,n) % returns two matrices
for i = 1:n L(i,1) = A(i,1);
end
for j = 1:n U(1,j) = A(1,j)/L(1,1);
end
for j = 2:n for i = j:n sum = 0.0; for k = 1:(j-1) sum = sum + L(i,k) * U(k,j); end L(i,j) = A(i,j) - sum; end U(j,j) = 1; for i = (j+1):n sum = 0.0; for k = 1:(j-1) sum = sum + L(j,k) * U(k,i); end U(j,i) = (A(j,i) - sum)/L(j,j); end
end
$\endgroup$ 3 $\begingroup$

The tridiagonal part can be created using sums of calls to diag()

n = 5 ;
nOnes = ones(n, 1) ;
x = diag(2 * nOnes, 0) - diag(nOnes(1:n-1), -1) - diag(nOnes(1:n-1), 1)
x = 2 -1 0 0 0 -1 2 -1 0 0 0 -1 2 -1 0 0 0 -1 2 -1 0 0 0 -1 2
$\endgroup$ $\begingroup$

In your case

toeplitz([2 -1 zeros(1, N-2)], [2 -1 zeros(1, N-2)])

or even

toeplitz([2 -1 zeros(1, N-2)])
$\endgroup$ $\begingroup$

You could also use conv2 to create a tridiagonal matrix

B = conv2(eye(5),[-1 2 -1],'same');
B = 2 -1 0 0 0
-1 2 -1 0 0 0 -1 2 -1 0 0 0 -1 2 -1 0 0 0 -1 2
$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like