フィルターのクリア

Need help creating an array

2 ビュー (過去 30 日間)
Marnie
Marnie 2015 年 4 月 3 日
編集済み: James Tursa 2015 年 4 月 3 日
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

採用された回答

Roger Stafford
Roger Stafford 2015 年 4 月 3 日
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);

その他の回答 (1 件)

James Tursa
James Tursa 2015 年 4 月 3 日
編集済み: James Tursa 2015 年 4 月 3 日
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;

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by