我阅读了一篇关于 MATLAB 中正确内存使用的有趣文章。这是:Link at official website 在这里我看到了例子:
If your data contains many zeros, consider using sparse arrays, which store only nonzero elements. The following example compares the space required for storage of an array of mainly zeros:
A = diag(1e3,1e3); % Full matrix with ones on the diagonal
As = sparse(A) % Sparse matrix with only nonzero elements
我尝试在我的代码中实现它并发现有趣的时刻:
A = diag(1e3,1e3)
不会创建对角线为 1 的矩阵!它创建只有一个非零元素的零矩阵:
clear A
A = diag(1e3,1e3);
find(A);
ans =
1001001
A(1001001)
ans =
1000
好的。我在帮助中阅读了有关 diag
功能的信息,并看到了这一点:
D = diag(v) returns a square diagonal matrix with the elements of vector v on the main diagonal.
好的!因此,如果 v
由 1 个元素组成,它实际上不会创建对角矩阵!是不是帮错了?
但。还有一个问题:为什么会这样?
diag(5,5)
ans =
0 0 0 0 0 5
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
我希望得到 5
值为 (1,1) 或 (5,5) 的矩阵 5x5。为什么它创建 6x6 矩阵以及为什么 5
是 (1,6) 元素?
最佳答案
手册:diag 您正在使用 diag 的第二个重载版本:
D = diag(v,k) places the elements of vector v on the kth diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.
因此,您的命令 A = diag(5,5) 将构造一个矩阵,其中主对角线上方第 5 个对角线的对角线元素将等于向量 [5]。因此,只有 A(1,6) 有值的结果值。
如果你想要一个 1e3x1e3 的矩阵,在对角线上尝试
A = diag(ones(1,1e3));
关于MATLAB 手动错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33919076/