How do I create this full diagonal matrix

10 ビュー (過去 30 日間)
Matthew Jones
Matthew Jones 2022 年 3 月 21 日
コメント済み: Matthew Jones 2022 年 3 月 21 日
this is the question
and this is my code (in a fucntion file) however it is not working, could anyone help me please?
  2 件のコメント
Rik
Rik 2022 年 3 月 21 日
Your code does exactly what you tell it to, which (unfortunately) isn't what you need.
Have a look at those lines. You tell Matlab to loop through 2 lines of code. Fine so far. However, you overwrite the results of both x and v on every iteration. Which one is supposed to be your output array? (You also forgot the ; to suppress the output)
Also, there may be several shortcuts: half of the matrix is the mirror of the other, so you only need a way to create one half.
In words, what step do you think you need to take to fill this array? Put a % before every step and then try to write the code. First start explaining, then write code. You tried the shortcut, it didn't work, so now you need to 'do it well'. Show the steps and I will try to help you fill in the code gaps.
Matthew Jones
Matthew Jones 2022 年 3 月 21 日
Thanks so much for the help, my problem was with overwritting the matrix each time but have fixed it now, would you have written the code a different way?

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

回答 (4 件)

Jan
Jan 2022 年 3 月 21 日
This is a Toeplitz matrix. See:
doc toeplitz

John D'Errico
John D'Errico 2022 年 3 月 21 日
  1. What are you doing with the matrix x, once you create a matrix with the diagonal in question? Does MATLAB know what you are doing with those diagonals? Should it be able to read your mind? Do you want to accumulate those diagonals in a matrix, rather than creating the matrix x over and over again? How could you do that?
  2. Why does your loop run from 0 to n? There are 2*n-1 diagonals in such a matrix anyway.
When you have a problem with code, learn to use the debugger if you are confused about what the code is doing. Look at each line of code, and what it produces.
  1 件のコメント
Matthew Jones
Matthew Jones 2022 年 3 月 21 日
Thanks for the help, fixed it now!

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


Torsten
Torsten 2022 年 3 月 21 日
n = 10;
A = zeros(n);
for i=1:n-1
A = A + diag((n-i)*ones(n-i,1),i) + diag((n-i)*ones(n-i,1),-i)
end
A = A + n*eye(n)
  1 件のコメント
Matthew Jones
Matthew Jones 2022 年 3 月 21 日
Thank you this really helped

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


Bruno Luong
Bruno Luong 2022 年 3 月 21 日
n = 5;
A = n-abs((1:n)'-(1:n))
A = 5×5
5 4 3 2 1 4 5 4 3 2 3 4 5 4 3 2 3 4 5 4 1 2 3 4 5

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by