How do I create this full diagonal matrix

조회 수: 16 (최근 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.

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)

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 CenterFile Exchange에서 Creating 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