how to generate matrix with any size in same pattern

3 次查看(过去 30 天)
-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