# Tridiagonal Matrix

John Stevens

Greenhorn

Posts: 5

posted 12 years ago

I am trying to construct a tridiagonal matrix.

The stipulation of this kind of matrix is the number of rows is equal to the number of columns and non-zero entries should only exist on the main diagonal and above and below the main diagonal e.g. this 6x6 array.

6 8 0 0 0 0

2 6 3 0 0 0

0 3 6 3 0 0

0 0 9 6 1 0

0 0 0 5 6 5

0 0 0 0 1 6

The main diagonal elements of this matrix are 6, 6, 6, 6, 6, 6.

How can I implement a program that obeys these rules when for example I want a user to enter the the size of the matrix and values in this matrix?

Thanks for the help

The stipulation of this kind of matrix is the number of rows is equal to the number of columns and non-zero entries should only exist on the main diagonal and above and below the main diagonal e.g. this 6x6 array.

6 8 0 0 0 0

2 6 3 0 0 0

0 3 6 3 0 0

0 0 9 6 1 0

0 0 0 5 6 5

0 0 0 0 1 6

The main diagonal elements of this matrix are 6, 6, 6, 6, 6, 6.

How can I implement a program that obeys these rules when for example I want a user to enter the the size of the matrix and values in this matrix?

Thanks for the help

posted 12 years ago

some thoughts for doing it quick and dirty...

i'd get the size, then create a 2-d array.

assuming you enter the data for the positions left to right, top to bottom,

you just read data for the array. the first row will have 2 (in [row,row] and [row,row+1]) elements (unless the array is 1x1), the last row will have 2 elements (in [row,row-1] and [row,row]), and every other row has 3 ([row,row-1], [row,row], [row,row+1]

so something like:

get size;

for (int row = 0; row < size; row++)

if row == 0

get one element [row,row]

if size > 1

get second element [row, row+1]

else if row == size - 1 //last row only has two datums in it

get 2 elements

else

get 3 elements

this might help. i'm sure there are better ways, but this might get you going....

i'd get the size, then create a 2-d array.

assuming you enter the data for the positions left to right, top to bottom,

you just read data for the array. the first row will have 2 (in [row,row] and [row,row+1]) elements (unless the array is 1x1), the last row will have 2 elements (in [row,row-1] and [row,row]), and every other row has 3 ([row,row-1], [row,row], [row,row+1]

so something like:

get size;

for (int row = 0; row < size; row++)

if row == 0

get one element [row,row]

if size > 1

get second element [row, row+1]

else if row == size - 1 //last row only has two datums in it

get 2 elements

else

get 3 elements

this might help. i'm sure there are better ways, but this might get you going....

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors