## how to generate matrix with any size in same pattern

### yibin (view profile)

on 22 Apr 2013
``` -2     1     0     0     0     0
1    -2     1     0     0     0
0     1    -2     1     0     0
0     0     1    -2     1     0
0     0     0     1    -2     1
0     0     0     0     1    -2```

i need to generate a matrix with pattern like this. how to write a script that the required pattern

for example, if i need 5*5 matrix with the required pattern it will be like this

``` -2     1     0     0     0
1    -2     1     0     0
0     1    -2     1     0
0     0     1    -2     1
0     0     0     1    -2```

or i need 7*7 matrix

``` -2     1     0     0     0     0     0
1    -2     1     0     0     0     0
0     1    -2     1     0     0     0
0     0     1    -2     1     0     0
0     0     0     1    -2     1     0
0     0     0     0     1    -2     1
0     0     0     0     0     1    -2 ```

per isakson

on 22 Apr 2013

Homework?

## Products

No products are associated with this question.

on 22 Apr 2013

### Andrei Bobrov (view profile)

on 22 Apr 2013
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 22 Apr 2013
```n = 5;
out = full(spdiags(ones(n,1)*[1 -2 1],-1:1,n,n));
```

or

```out = zeros(n);
out([2:n+1:end,n+1:n+1:end]) = 1;
out(1:n+1:end) = -2;
```

or

```out = zeros(n);
z = diag(true(n-1,1),-1);
out(z | z') = 1;
out(eye(n) > 0) = -2;
```