Rakesh Adhikesavan
Rakesh Adhikesavan

Reputation: 12816

How do I create this matrix on Matlab?

I am trying to create a matrix (32 x 32) with -1 on its main diagonal and 1 in its first and second superdiagonals. 0 everywhere else.

A = eye(32)* -1;

That gives me a matrix with -1 on its main diagonal, how do I proceed?

Upvotes: 0

Views: 373

Answers (8)

Luis Mendo
Luis Mendo

Reputation: 112659

Yet another approach: this uses convmtx from the Signal Processing Toolbox:

n = 32; %// matrix size
v = [-1 1 1]; %// vector with values
M = convmtx(v, n);
M = M(:,1:end-numel(v)+1);

Upvotes: 2

horchler
horchler

Reputation: 18484

Just using diag and eye:

n = 32;
z = ones(n-1,1);
A = diag(z,1)+diag(z(1:n-2),2)-eye(n);

There's also:

n = 32;
A = gallery('triw',n,1,2)-2*eye(n)

using the gallery function with the 'triw' option.

Upvotes: 5

rayryeng
rayryeng

Reputation: 104464

If I can suggest more esoteric code, first create a vector full of 1s, then create the identity matrix, then shift create a diagonal matrix with these 1s with the vector and shift it to the right by 1, decreasing the amount of elements in the vector, then do it again for the last superdiagonal.

n = 32;
vec = ones(n,1);
out = -eye(n) + diag(vec(1:end-1),1) + diag(vec(1:end-2),2);

Upvotes: 3

Daniel
Daniel

Reputation: 36710

diag allows you to create a matrix passing a diagonal:

-diag(ones(n,1),0)+diag(ones(n-1,1),1)+diag(ones(n-2,1),2)

Last parameter 0 for the main diagonal, 1 and 2 for the super diagonals.

Upvotes: 4

Adriaan
Adriaan

Reputation: 18177

N = 32;
A = -diag(ones(N,1)); % diagonal
tmp1=diag(ones(N-1,1),1); %1st supra
tmp1=diag(ones(N-2,1),2); @2nd supra
A = A+tmp1+tmp2; 

using diag

Upvotes: 2

TroyHaskin
TroyHaskin

Reputation: 8401

You can use spdiags to set the diagonals directly into a sparse matrix and full-it if desired.

n       = 32;
Asparse = spdiags(ones(n,1)*[-1,1,1],[0,1,2],n,n);
Afull   = full(Asparse);

Upvotes: 6

n=32;
toeplitz([-1; zeros(n-1,1)],[-1 1 1 zeros(1,n-3)])

is what you need. This will create a non-symmetric Toeplitz matrix (a band matrix), the first column of which is given by [-1; zeros(32-1,1)], the first row by [-1 1 1 zeros(1,32-3)]. You could also define a function with size n as input parameter, if necessary.

Upvotes: 7

Nitish
Nitish

Reputation: 7116

n = 32
A = -1*eye(n); %Create 32x32 Identity
A(n+1:n+1:n^2) = 1; %Set 1st Superdiagonal to 1
A(2*n+1:n+1:n^2) = 1; %Set 2nd Superdiagonal to 1

Note that MATLAB uses column-major order for matrices. For the 1st superdiagonal, we start with the (n+1)th element and choose every (n+1)th element thereon. We do a similar operation for 2nd superdiagonal except we start from (2*n+1)th element.

Upvotes: 5

Related Questions