How do I create this full diagonal matrix

10 Ansichten (letzte 30 Tage)
Matthew Jones
Matthew Jones am 21 Mär. 2022
Kommentiert: Matthew Jones am 21 Mär. 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 Kommentare
Rik
Rik am 21 Mär. 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 am 21 Mär. 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?

Melden Sie sich an, um zu kommentieren.

Antworten (4)

Jan
Jan am 21 Mär. 2022
This is a Toeplitz matrix. See:
doc toeplitz

John D'Errico
John D'Errico am 21 Mär. 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.

Torsten
Torsten am 21 Mär. 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)

Bruno Luong
Bruno Luong am 21 Mär. 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

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by