how to generate matrix with any size in same pattern

조회 수: 1 (최근 30일)
yibin
yibin 2013년 4월 22일
편집: Andrei Bobrov 2019년 12월 12일
-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

답변 (3개)

Walter Roberson
Walter Roberson 2013년 4월 22일

Andrei Bobrov
Andrei Bobrov 2013년 4월 22일
편집: Andrei Bobrov 2019년 12월 12일
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;
and (after 6.5 years ;)
n = 10;
out = toeplitz([-2 1 zeros(1,n-2)]);

Bandar
Bandar 2019년 12월 12일
n=5;
v =-2*ones(1,n);
p =ones(1,n-1);
B =diag(v);
C =diag(p,1);
D =diag(p,-1);
A=B+C+D
The result is
A =
-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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by