I am currently trying to create a 500*500 matrix in matlab with diagonals a=-1, b=4, c=2. My teacher has said that the best way to go about it is using loops, but is there a coded in function to use?

2 件のコメント

David Goodmanson
David Goodmanson 2019 年 11 月 11 日
Hi Aaron
check out the 'diag' function
Alex Treat
Alex Treat 2020 年 10 月 30 日
coughs you were in the mec 103 class at CSU...

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

 採用された回答

Stephen23
Stephen23 2019 年 11 月 11 日
編集済み: Stephen23 2022 年 3 月 20 日

11 投票

"My teacher has said that the best way to go about it is using loops"
Why on earth would they say that? Here are some non-loop aproaches:
2- Use diag :
>> N = 10;
>> a = -1;
>> b = 4;
>> c = 2;
>> M = diag(a*ones(1,N)) + diag(b*ones(1,N-1),1) + diag(c*ones(1,N-1),-1)
M =
-1 4 0 0 0 0 0 0 0 0
2 -1 4 0 0 0 0 0 0 0
0 2 -1 4 0 0 0 0 0 0
0 0 2 -1 4 0 0 0 0 0
0 0 0 2 -1 4 0 0 0 0
0 0 0 0 2 -1 4 0 0 0
0 0 0 0 0 2 -1 4 0 0
0 0 0 0 0 0 2 -1 4 0
0 0 0 0 0 0 0 2 -1 4
0 0 0 0 0 0 0 0 2 -1
3- indexing is reasonably simple:
>> M = zeros(N,N);
>> M( 1:1+N:N*N) = a;
>> M(N+1:1+N:N*N) = b;
>> M( 2:1+N:N*N-N) = c
M =
-1 4 0 0 0 0 0 0 0 0
2 -1 4 0 0 0 0 0 0 0
0 2 -1 4 0 0 0 0 0 0
0 0 2 -1 4 0 0 0 0 0
0 0 0 2 -1 4 0 0 0 0
0 0 0 0 2 -1 4 0 0 0
0 0 0 0 0 2 -1 4 0 0
0 0 0 0 0 0 2 -1 4 0
0 0 0 0 0 0 0 2 -1 4
0 0 0 0 0 0 0 0 2 -1

7 件のコメント

Juan Jesús Rocha Cuervo
Juan Jesús Rocha Cuervo 2020 年 4 月 9 日
How can I stop the output of "M" in this example?
Jonathan Wharrier
Jonathan Wharrier 2020 年 5 月 2 日
a semi-colon at the end of the line supresses output
giannit
giannit 2020 年 9 月 28 日
編集済み: giannit 2020 年 9 月 28 日
This can be done also using toeplitz
A = toeplitz( [-1 2 zeros(1,498)] , [-1 4 zeros(1,498)] ); % size = 2 MB
and since there are many zeros you can save space using sparse
B = toeplitz( sparse([1 1],[1 2],[-1 2],1,498) , sparse([1 1],[1 2],[-1 4],1,498) ); % size = 28 kB
Steven Lord
Steven Lord 2020 年 9 月 28 日
If you're creating this as a sparse matrix see spdiags.
Arth Patel
Arth Patel 2020 年 9 月 29 日
Can you please explain the second method a bit ? It's not clear to me how you're indexing a matrix using just one argument.
Stephen23
Stephen23 2020 年 10 月 30 日
"It's not clear to me how you're indexing a matrix using just one argument."
The second example uses linear indexing:
Ana Sarai
Ana Sarai 2025 年 2 月 22 日
Thank you, = )

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeOperating on Diagonal Matrices についてさらに検索

質問済み:

2019 年 11 月 11 日

コメント済み:

2025 年 2 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by