how to generate matrix with any size in same pattern

2 vues (au cours des 30 derniers jours)
yibin
yibin le 22 Avr 2013
Modifié(e) : Andrei Bobrov le 12 Déc 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

Réponses (3)

Walter Roberson
Walter Roberson le 22 Avr 2013

Andrei Bobrov
Andrei Bobrov le 22 Avr 2013
Modifié(e) : Andrei Bobrov le 12 Déc 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 le 12 Déc 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

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by