how to make the numbers on the matrix with alternative sign?

3 ビュー (過去 30 日間)
kingsley
kingsley 2017 年 2 月 15 日
編集済み: Walter Roberson 2024 年 8 月 9 日
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)
[rows, columns] = size(z)
z(1:2*rows+2:end) = -z(1:2*rows+2:end)
b=diag(y2,+1)
d=diag(y2,-1)
g=z+b+d

回答 (2 件)

praguna manvi
praguna manvi 2024 年 8 月 9 日
Please use the code below to generate a matrix with alternating signs.
% Define the size of the matrix
n = 5; % Example value, you can change this
sizeK = 2 * n;
% Initialize the matrix K with zeros
K = zeros(sizeK);
% Fill the main diagonal with alternating 2 and -2
for i = 1:sizeK
if mod(i, 2) == 1
K(i, i) = 2;
else
K(i, i) = -2;
end
end
% Fill the super-diagonal and sub-diagonal with alternating 1 and -1
for i = 1:sizeK-1
if mod(i, 2) == 1
K(i, i+1) = 1;
K(i+1, i) = 1;
else
K(i, i+1) = -1;
K(i+1, i) = -1;
end
end
% Display the matrix K
disp(K);
2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2

Stephen23
Stephen23 2024 年 8 月 9 日
編集済み: Stephen23 2024 年 8 月 9 日
n = 5;
m = toeplitz([2,1,zeros(1,2*n-2)]) .* -(-1).^gallery('minij',2*n)
m = 10x10
2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2 -1 0 0 0 0 0 0 0 0 -1 2 1 0 0 0 0 0 0 0 0 1 -2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

カテゴリ

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