Need help creating an array
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Marnie
am 3 Apr. 2015
Bearbeitet: James Tursa
am 3 Apr. 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
0 Kommentare
Akzeptierte Antwort
Roger Stafford
am 3 Apr. 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);
0 Kommentare
Weitere Antworten (1)
James Tursa
am 3 Apr. 2015
Bearbeitet: James Tursa
am 3 Apr. 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;
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!