Discover MakerZone

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

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

how to generate matrix with any size in same pattern

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 

1 Comment

per isakson on 22 Apr 2013

Homework?

yibin

Tags

Products

No products are associated with this question.

2 Answers

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;

0 Comments

Andrei Bobrov

Contact us