breeden
breeden

Reputation: 735

MATLAB Matrix construction advice

I need to use MATLAB to solve the following matrix equation:

Matrix Equation

This matrix is nxn, and I can construct most of the matrix using the following MATLAB code:

e = ones(n,1);
A = h^(-2)*spdiags([e (h^2 - 2)*e e], [-1 0 1], n, n);

What's a good way to change the first and last row? Perhaps it would be nice to just add a nice matrix B with the first row as [ 2/h 1/h^2 0 ... 0 0 0 ] and the last row as [ 0 0 0 ... 0 1/h^2 (2h + 1)/h^2] and just take A + B. How would you do this though?

Upvotes: 1

Views: 92

Answers (1)

David
David

Reputation: 8459

I think the simplest way is best in this case as you aren't modifying much of the matrix you have created:

A(1,:)=A(1,:)+[2/h 1/h^2 zeros(1,n-2)];
A(n,:)=A(n,:)+[zeros(1,n-2) 1/h^2 2/h];

or even replace individual elements rather than rows.

Upvotes: 2

Related Questions