mpalmero
mpalmero

Reputation: 23

Creating specific big matrix in matlab

My question is how can I create the same type of matrix in a matlab program such that it keeps the same logic, that is 10s in the main diagonal, then 3s in the upper and lower diagonal surrounding the main diagonal, and ones in the diagonals above and below the 3s and 0s in other cases, and that I can be able to modify for whatever NxN I'd like?

something like this for a 6x6 case

A = [10  3  1  0  0  0 ; 
      3 10  3  1  0  0 ;
      1  3 10  3  1  0 ; 
      0  1  3 10  3  1 ; 
      0  0  1  3 10  3 ;
      0  0  0  1  3 10 ];

Upvotes: 2

Views: 258

Answers (2)

Shai
Shai

Reputation: 114826

For very large matrices (N=10000) you'll have to use sparse matrix.
Consider the following construction using spdiags

function A = largeSparseMatrix( N )
%
% construct NxN sparse matrix with 10 on main diagonal, 
% 3 on the first off-diagonals and 1 on the second off-diagonals
%
B = ones(N, 5); % pre-allocate for diagonals
B(:,1) = 10;  % main diagonal d(1) = 0
B(:,2:3) = 3; % first off diagonal
B(:,4:5) = 1; % second off-diagonal
d = [ 0 , 1, -1, 2, -2 ]; % mapping columns of B to diagonals of A
A = spdiags( B, d, N, N ); % TA-DA!

Note that some of the entries in B are ignored in the construction of A.
See the manual of spdiags for more info.

Upvotes: 3

JustinBlaber
JustinBlaber

Reputation: 4650

Code:

toeplitz([10  3  1  0  0  0])

Output:

ans =

    10     3     1     0     0     0
     3    10     3     1     0     0
     1     3    10     3     1     0
     0     1     3    10     3     1
     0     0     1     3    10     3
     0     0     0     1     3    10

Upvotes: 3

Related Questions