フィルターのクリア

how to generate matrix with any size in same pattern

3 ビュー (過去 30 日間)
yibin
yibin 2013 年 4 月 22 日
編集済み: Andrei Bobrov 2019 年 12 月 12 日
-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

回答 (3 件)

Walter Roberson
Walter Roberson 2013 年 4 月 22 日

Andrei Bobrov
Andrei Bobrov 2013 年 4 月 22 日
編集済み: Andrei Bobrov 2019 年 12 月 12 日
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 2019 年 12 月 12 日
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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by