MATLAB diag & spdiags函数的使用

diag & spdiags函数的使用:
下面对diag 函数和spdiags函数进行了实例演示,特别注意的是spdiags函数:
1.[Bout,d] = spdiags(A)
矩阵A:mn,
当m<n时,主对角线下方的对角线顶部补0,主对角线上方的对角线底部补0。从左到右,依次组成了Bout的列,d为A中各对角线的序号。
当m>=n时,主对角线下方的对角线底部补0,主对角线上方的对角线顶部补0。从左到右,依次组成了Bout的列,d为A中各对角线的序号。
2.A = spdiags(Bin,d,m,n)
创建一个m
n的矩阵(创建矩阵A:mn),大小为mn,其中矩阵A的对角线是以Bin中的几个列得出来的。也就是说,从左到右按顺序,Bin中的几个列作为A的对角线。如果Bin中若些列元素较多,则按上述方法补0的方法去掉(此时不是补0,而是舍去)。

clc;clear;close all;
format compact

%% diag V=diag(A,k)
A1=[1 0 0;-2 3 0;0 0 3];
% V=diag(A,k)
% k=0 : Major diagonal,k<1:lower left, k>1:upper right
v0=diag(A1,0);
v_1=diag(A1,-1);
v1=diag(A1,1);

%% spdiags [Bout,d] = spdiags(A)
A=[0,5,0,10,0,0;
   0,0,6,0,11,0;
   3,0,0,7,0,12;
   1,4,0,0,8,0;
   0,2,5,0,0,9];
% Extract the nonzero diagonals 
[Bout,d] = spdiags(A);

% B:m*n  
% m>=n: 
% Add 0 at the bottom of the left lower of the main diagonal
% Add 0 at the top of the upper right of the main diagonal
% m<n: 
% Add 0 at the top of the left lower of the main diagonal
% Add 0 at the bottom of the upper right of the main diagonal
B1=[1 2 3;4 5 6;7 8 9;10 11 12]; % m>n
[Bout1,d1] = spdiags(B1);

B2=[1 2 3 4;5 6 7 8;9 10 11 12]; % m<=n
[Bout2,d2] = spdiags(B2);

%% spdiags  A3 = spdiags(Bin,d,m,n)
% Use spdiags to create a square 5-by-5 matrix with several of the columns of Bin as diagonals.
Bin=[1 6 11;2 7 12;3 8 13;4 9 17;5 10 15]
A3=full(spdiags(Bin,[-2 0 2],5,5))
% A3=full(spdiags(Bin,[-2 0 1 2],5,5)); % error,Bin only three columns.
% A3=full(spdiags(Bin,[-2 0],5,5)); % Use only the first two columns in Bin.

参考:
1.matlab中的diag,spdiags函数
2.MATLAB中国

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值