MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today**New to MATLAB?**

Asked by yibin
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

*No products are associated with this question.*

Answer by Walter Roberson
on 22 Apr 2013

Answer by Andrei Bobrov
on 22 Apr 2013

Edited by Andrei Bobrov
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;

## 1 Comment

## per isakson (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/73045#comment_144679

Homework?