how to make the main diagonal of K are alternatively 2 and -2’s

1 回表示 (過去 30 日間)
kingsley
kingsley 2017 年 2 月 15 日
コメント済み: kingsley 2017 年 2 月 16 日
How to get alternative signs for the numbers on the diagonal of a matrix
  2 件のコメント
John D'Errico
John D'Errico 2017 年 2 月 15 日
What have you tried? For example, a simple loop would suffice.
Or, you could get trickier, and use the diag function.
John D'Errico
John D'Errico 2017 年 2 月 15 日
編集済み: John D'Errico 2017 年 2 月 15 日
Please don't add new questions just to add additional information to an existing question. I have moved the separate question by this individual into a comment:
I want to create a matrix that the main diagonal of K are alternatively 2 and -2’s, the sub- and sup-diagonal of K alternatively 1 and -1’s, and everywhere else 0. The size of K is 2n by 2n.
Here is what I got so far.
x=ones(1,5);
y=ones(1,4);
x2=2*x;
y2=y*-1;
z=diag(x2,0)+diag(y2,+1)
d=diag(y2,-1)
g=z+d

サインインしてコメントする。

回答 (2 件)

Image Analyst
Image Analyst 2017 年 2 月 15 日
One way, of many:
K = 2 * eye(5)
[rows, columns] = size(K)
K(1:2*rows+2:end) = -K(1:2*rows+2:end)

John D'Errico
John D'Errico 2017 年 2 月 15 日
編集済み: John D'Errico 2017 年 2 月 15 日
So you want to create a tridiagonal matrix, with the main diagonal alternating +/- 2, and the sub and super diagonals alternating +/- 1?
n = 5;
k = mod(1:n,2)*2 - 1;
A = diag(k*2) + diag(k(1:n-1),-1) + diag(k(1:n-1),1)
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
A loop would have been nearly as easy, but not really necessary if you know the tools in MATLAB.
The best solution (IMHO) is to use spdiags.

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by