%%%% Setup the matrix for 1D Laplacian in sparse format, with some perturbation %%%% to help you distinguish column and row indices. clear all % format long N = 10; %N = 100; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Setup the storage for non-zero entries %%%% IA = the storage for index i %%%% JA = the storage for index j %%%% KA = the storage for entry values IA = zeros(N-1+2*(N-2),1); % only three diagonals are nonzero; % allocate a big vector to store i for those (i,j) JA = IA ; % to store those j KA = IA ; % to store those A(i,j) % Store the first nonzero entry: A(i,j) with i=1, j=1 k = 1 ; IA(k) = 1 ; JA(k) = IA(k) ; KA(k) = -2 ; % Store A(i,j) with i=1, j=2 k = k + 1 ; IA(k) = 1 ; JA(k) = IA(k) + 1 ; KA(k) = 1.01 ; %%%% Now, proceed to store the remaining nonzero entries. for i = 2 : N-2 k = k + 1 ; IA(k) = i ; JA(k) = IA(k) -1 ; KA(k) = 1 ; k = k + 1 ; IA(k) = i ; JA(k) = IA(k) ; KA(k) = -2 ; k = k + 1 ; IA(k) = i ; JA(k) = IA(k) + 1 ; KA(k) = 1.01 ; end k = k + 1 ; IA(k) = N-1 ; JA(k) = IA(k) -1 ; KA(k) = 1 ; k = k + 1 ; IA(k) = N-1 ; JA(k) = IA(k) ; KA(k) = -2 ; A = sparse(IA,JA,KA) % After you have actually seen the matrix A in matlab, % you can switch last line to the one below % A = sparse(IA,JA,KA);