Matlab spdiags function not do what I expect

27 ビュー (過去 30 日間)
Zeyuan
Zeyuan 2025 年 2 月 3 日 17:11
編集済み: Stephen23 2025 年 2 月 3 日 20:11
B=[1 2 3;4 5 6;7 8 9;10 11 12]
d=[-3 0 2];
A=spdiags(B,d,4,7); %主对角线之下的对角线溢出时候,取最后一个值
B=spdiags(B,d,7,4); %主对角线之上的对角线溢出时候,取最后一个值
C=spdiags(B,d,4,4);
full(A)
full(B)
full(C)
Why would I get
ans =
2 0 3 0 0 0 0
0 5 0 6 0 0 0
0 0 8 0 9 0 0
10 0 0 11 0 12 0
ans =
2 0 9 0
0 5 0 12
0 0 8 0
1 0 0 11
0 4 0 0
0 0 7 0
0 0 0 10
ans =
0 0 8 0
0 5 0 0
0 0 0 0
2 0 0 0
Why is C so different from the previous two? In terms of having the numbers not shown on main diagnol and also having the numbers arranged from bottom to top?
  1 件のコメント
Stephen23
Stephen23 2025 年 2 月 3 日 17:29
Remember to click the accept button for the answer that best resolves your original question. For example here:
youu have an answer which correctly resolves your question. It would be polite to accept it.

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

採用された回答

Stephen23
Stephen23 2025 年 2 月 3 日 17:25
編集済み: Stephen23 2025 年 2 月 3 日 17:28
"Why is C so different from the previous two?"
Look at your code! On this line you completely overwite B with a completely different variable:
B=spdiags(B,d,7,4);
^ new ^ old
Of course all following lines will refer to that new B, not any old B that might have existed previously.
Solution: do not reuse variable names:
M = [1,2,3;4,5,6;7,8,9;10,11,12]
M = 4×3
1 2 3 4 5 6 7 8 9 10 11 12
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
d = [-3,0,2];
A = spdiags(M,d,4,7);
B = spdiags(M,d,7,4);
C = spdiags(M,d,4,4);
full(A)
ans = 4×7
2 0 3 0 0 0 0 0 5 0 6 0 0 0 0 0 8 0 9 0 0 10 0 0 11 0 12 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
full(B)
ans = 7×4
2 0 9 0 0 5 0 12 0 0 8 0 1 0 0 11 0 4 0 0 0 0 7 0 0 0 0 10
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
full(C)
ans = 4×4
2 0 9 0 0 5 0 12 0 0 8 0 1 0 0 11
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  2 件のコメント
Zeyuan
Zeyuan 2025 年 2 月 3 日 19:51
You answered part of my question. My next question would be: why in C, the -3rd diagnol is 1, the first number in col1 of M, while in A, the -3rd diagnol is 10, the last number in col1 of M? In other words, why when spill over, in A, the last number is accepted and in C the first number is accepted?
Stephen23
Stephen23 2025 年 2 月 3 日 20:05
編集済み: Stephen23 2025 年 2 月 3 日 20:11
"In other words, why when spill over, in A, the last number is accepted and in C the first number is accepted"
The SPDIAGS documentation explains that behavior here:
The diagrams in the help neatly illustrate its behavior. Basically you can think of it as slanting those columns at 45 degrees and then selecting the submatrix of the requested size.

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by