how to generate matrix with any size in same pattern

2 visualizaciones (últimos 30 días)
yibin
yibin el 22 de Abr. de 2013
Editada: Andrei Bobrov el 12 de Dic. de 2019
-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

Respuestas (3)

Walter Roberson
Walter Roberson el 22 de Abr. de 2013

Andrei Bobrov
Andrei Bobrov el 22 de Abr. de 2013
Editada: Andrei Bobrov el 12 de Dic. de 2019
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 el 12 de Dic. de 2019
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

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by