How do I create this full diagonal matrix

10 vues (au cours des 30 derniers jours)
Matthew Jones
Matthew Jones le 21 Mar 2022
Commenté : Matthew Jones le 21 Mar 2022
this is the question
and this is my code (in a fucntion file) however it is not working, could anyone help me please?
  2 commentaires
Rik
Rik le 21 Mar 2022
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 le 21 Mar 2022
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?

Connectez-vous pour commenter.

Réponses (4)

Jan
Jan le 21 Mar 2022
This is a Toeplitz matrix. See:
doc toeplitz

John D'Errico
John D'Errico le 21 Mar 2022
  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 commentaire
Matthew Jones
Matthew Jones le 21 Mar 2022
Thanks for the help, fixed it now!

Connectez-vous pour commenter.


Torsten
Torsten le 21 Mar 2022
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 commentaire
Matthew Jones
Matthew Jones le 21 Mar 2022
Thank you this really helped

Connectez-vous pour commenter.


Bruno Luong
Bruno Luong le 21 Mar 2022
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

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by