matlab自带的函数spdiags功能测试

测试实例

选取A矩阵如下所示
(1) [ 5 0 3 0 0 1 6 0 4 0 0 2 7 0 5 0 0 3 8 0 3 0 0 0 9 ] \left[ \begin{matrix} 5 & 0 & 3 &0 &0 \\ 1 &6 & 0 &4 &0 \\ 0 & 2 & 7 & 0 &5\\ 0 & 0& 3 &8 &0 \\ 3& 0&0 &0 &9 \end{matrix} \right] \tag{1}

  1. 运行如下命令

B2=spdiags(A,[2,3]) %按对角提取2,3行元素组成一个矩阵

结果如下
(2) [ 0 0 0 0 3 0 4 0 5 0 ] \left[ \begin{matrix} 0 & 0 \\ 0 &0 \\ 3 & 0 \\ 4 & 0 \\ 5& 0 \end{matrix} \right] \tag{2}
2. 运行如下命令

spdiags([-3;-3],-3,A) %用B替换A的部分元素,其中最后结果为稀疏矩阵。
full(B3)

结果如下
(3) [ 5 0 3 0 0 1 6 0 4 0 0 2 7 0 5 3 0 3 8 0 3 3 0 0 9 ] \left[ \begin{matrix} 5 & 0 & 3 &0 &0 \\ 1 &6 & 0 &4 &0 \\ 0 & 2 & 7 & 0 &5\\ -3 & 0& 3 &8 &0 \\ 3& -3&0 &0 &9 \end{matrix} \right] \tag{3}
3. 运行如下命令

B4=spdiags([ones(5,1),2ones(5,1),1.5ones(5,1)],[-1,0,1],5,5)
full(B4) %把稀疏矩阵变为一般矩阵形式。

结果如下
(4) [ 2.0000 1.5000 0 0 0 1.0000 2.0000 1.5000 0 0 0 1.0000 2.0000 1.5000 0 0 0 1.0000 2.0000 1.5000 0 0 0 1.0000 2.0000 ] \left[ \begin{matrix} 2.0000 &1.5000 & 0 & 0 & 0\\ 1.0000 &2.0000 & 1.5000 & 0 & 0\\ 0 &1.0000 & 2.0000 & 1.5000 & 0\\ 0 & 0 & 1.0000 &2.0000 &1.5000\\ 0 & 0 & 0 &1.0000 & 2.0000 \end{matrix} \right] \tag{4}

测试程序的代码如下

%测试matlab自带的函数spdiags
%稀疏矩阵设置
A=diag([1 2 3 0],-1)+diag([5 6 7 8 9],0)+diag([3 4 5],2);A(5,1)=3;
%%
A
B1=spdiags(A) %按对角稀疏存储该矩阵,改变了矩阵大小
%B = spdiags(A,d) extracts the diagonals specified by d.
B2=spdiags(A,[2,3]) %按对角提取2,3行元素组成一个矩阵
% A = spdiags(B,d,A) replaces the diagonals of A specified by d with the columns of B.  The output is sparse.
B3=spdiags([-3;-3],-3,A) %用B替换A的部分元素,其中最后结果为稀疏矩阵。
size(B3)  %仅仅是稀疏存储,本质上还是5*5矩阵
B3*ones(5,1)  %可以直接相乘
% A = spdiags(B,d,m,n) creates an m-by-n sparse matrix from the columns of B and places them along the diagonals specified by d.
B4=spdiags([ones(5,1),2*ones(5,1),1.5*ones(5,1)],[-1,0,1],5,5) 
full(B4)   %把稀疏矩阵变为一般矩阵形式。

猜你喜欢

转载自blog.csdn.net/sinat_30967935/article/details/82945302