Effacer les filtres
Effacer les filtres

Need help creating an array

2 vues (au cours des 30 derniers jours)
Marnie
Marnie le 3 Avr 2015
Modifié(e) : James Tursa le 3 Avr 2015
I want to create the following array:
A = [-4 2 0 0 0; 2 -4 2 0 0; 0 2 -4 2 0; 0 0 2 -4 2; 0 0 0 2 -4];
' That's easy enough but I want to know if there is a way to make it neater, and also capable of being expanded to a higher number of rows.
So far I have tried: I = eye(5,5) .* -4
I = [-4 0 0 0 0; 0 -4 0 0 0; 0 0 -4 0 0; 0 0 0 -4 0; 0 0 0 0 -4];
Which is close, I guess. But need the two's in the columns aswell.
Thanks in advance

Réponse acceptée

Roger Stafford
Roger Stafford le 3 Avr 2015
Do either of these two:
n = 10; % <-- you choose n
A = diag(-4*ones(n,1))+diag(2*ones(n-1,1),1)+diag(2*ones(n-1,1),-1);
or
n = 10; % <-- you choose n
t = [-4,2,zeros(1,n-2)];
A = toeplitz(t,t);

Plus de réponses (1)

James Tursa
James Tursa le 3 Avr 2015
Modifié(e) : James Tursa le 3 Avr 2015
And another way:
A = full(spdiags(repmat([2 -4 2],n,1),[-1 0 1],n,n));
And yet another way:
A = -4*eye(n);
A(2:n+1:end) = 2;
A(n+1:n+1:end) = 2;

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by