Need help creating an array
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
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);
0 件のコメント
その他の回答 (1 件)
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;
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!