How to write a diagonal rectangular matrix

7 ビュー (過去 30 日間)
Leonardo
Leonardo 2023 年 11 月 23 日
コメント済み: Dyuman Joshi 2023 年 11 月 23 日
I have to insert on matlab this matrix:
n = 100;
A = diag(21*ones(n,1)) + diag(-4*ones(n-1,1),-1)...
+ diag(-20*ones(n-1,1),1) + diag(ones(n-2,1),-2)...
+ diag(2*ones(n-2,1), 2);
I can generate it when it is squared, but now the exercise tells me to use the same numbers in a rectangular matrix having dimensions 100x98: how do I create the new matrix?

採用された回答

Chunru
Chunru 2023 年 11 月 23 日
編集済み: Chunru 2023 年 11 月 23 日
You can use toeplitz function.
% Smaller n, m here
n = 10;
m = 8;
A = diag(21*ones(n,1)) + diag(-4*ones(n-1,1),-1)...
+ diag(-20*ones(n-1,1),1) + diag(ones(n-2,1),-2)...
+ diag(2*ones(n-2,1), 2);
whos
Name Size Bytes Class Attributes A 10x10 800 double cmdout 1x33 66 char m 1x1 8 double n 1x1 8 double
A
A = 10×10
21 -20 2 0 0 0 0 0 0 0 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 0 0 0 0 0 0 0 1 -4 21
c = zeros(n, 1); c(1:3)=[21 -4 1]; % 1st column
r = zeros(m, 1); r(1:3)=[21 -20 2]; % 1st row
B = toeplitz(c, r)
B = 10×8
21 -20 2 0 0 0 0 0 -4 21 -20 2 0 0 0 0 1 -4 21 -20 2 0 0 0 0 1 -4 21 -20 2 0 0 0 0 1 -4 21 -20 2 0 0 0 0 1 -4 21 -20 2 0 0 0 0 1 -4 21 -20 0 0 0 0 0 1 -4 21 0 0 0 0 0 0 1 -4 0 0 0 0 0 0 0 1
  3 件のコメント
Leonardo
Leonardo 2023 年 11 月 23 日
How can I remove the last two columns easily? @Dyuman Joshi
Dyuman Joshi
Dyuman Joshi 2023 年 11 月 23 日
% Smaller n, m here
n = 10;
m = 8;
A = diag(21*ones(n,1)) + diag(-4*ones(n-1,1),-1)...
+ diag(-20*ones(n-1,1),1) + diag(ones(n-2,1),-2)...
+ diag(2*ones(n-2,1), 2)
A = 10×10
21 -20 2 0 0 0 0 0 0 0 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 2 0 0 0 0 0 0 1 -4 21 -20 0 0 0 0 0 0 0 1 -4 21
%Remove the last n-m columns
A(:,end-(1:n-m)) = []
A = 10×8
21 -20 2 0 0 0 0 0 -4 21 -20 2 0 0 0 0 1 -4 21 -20 2 0 0 0 0 1 -4 21 -20 2 0 0 0 0 1 -4 21 -20 2 0 0 0 0 1 -4 21 -20 0 0 0 0 0 1 -4 21 0 0 0 0 0 0 1 -4 2 0 0 0 0 0 0 1 -20 0 0 0 0 0 0 0 21

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by