矩阵sum_Matlab: 如何对矩阵的部分行/列求和

Matlab里的sum函数可以用于求和。

先简单来介绍一下sum函数,对一个矩阵A而言,

(1) sum(A,'all'): 对矩阵A的所有元素进行求和,返回的是一个标量

(2) sum(A,1): 对矩阵A的每一列进行求和,返回的是一个行向量

(3) sum(A,2): 对矩阵A的每一行进行求和,返回的是一个列向量

对矩阵A的部分行/列进行求和,可以用:

sum(A(:,m:n),2): 对矩阵A每一行的第m到n列进行求和,返回一个列向量

或者

sum(A(m:n,:),1):对每一列的第m到n行进行求和,返回一个行向量。

举例:

对矩阵ATEST每一行的第2-6列进行求和:

ATEST =ones(6,6)

ATEST_SUM = sum(ATEST(:,2:6),2)

运算结果如下:

18d19aa1855287db56d9c84dfed5094f.png

其他求和功能,如根据某个标准进行求和,对表格数据进行求和,可参考以下链接。

参考文献:

  1. https://de.mathworks.com/help/matlab/ref/sum.html

2. https://nl.mathworks.com/matlabcentral/answers/73970-how-to-sum-part-of-a-column

3. https://nl.mathworks.com/matlabcentral/answers/462811-sum-specific-colums-based-on-a-criteria

4. https://nl.mathworks.com/matlabcentral/answers/382516-how-to-sum-a-specified-portion-of-a-column-in-a-data-table

5. https://nl.mathworks.com/matlabcentral/answers/342903-how-to-sum-some-columns-of-a-matrix

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MATLAB实现: ```matlab % 矩阵LU分解 function [L,U] = lu_decomposition(A) n = size(A,1); L = eye(n); U = A; for i=1:n-1 if abs(U(i,i)) < eps error('Zero pivot encountered'); end for j=i+1:n L(j,i) = U(j,i) / U(i,i); U(j,:) = U(j,:) - L(j,i)*U(i,:); end end end % 矩阵求和 function S = matrix_sum(A) S = sum(sum(A)); end % 测试 A = [1 2 3; 4 5 6; 7 8 9]; [L,U] = lu_decomposition(A); S = matrix_sum(A); disp('A='); disp(A); disp('L='); disp(L); disp('U='); disp(U); disp('sum(A)='); disp(S); ``` C++实现: ```c++ #include <iostream> #include <vector> using namespace std; // 矩阵LU分解 void lu_decomposition(vector<vector<double>>& A, vector<vector<double>>& L, vector<vector<double>>& U) { int n = A.size(); L = vector<vector<double>>(n, vector<double>(n, 0)); U = A; for(int i=0;i<n-1;i++) { if(abs(U[i][i]) < 1e-6) { throw "Zero pivot encountered"; } for(int j=i+1;j<n;j++) { L[j][i] = U[j][i] / U[i][i]; for(int k=i;k<n;k++) { U[j][k] -= L[j][i] * U[i][k]; } } } for(int i=0;i<n;i++) { L[i][i] = 1; } } // 矩阵求和 double matrix_sum(vector<vector<double>>& A) { double S = 0; for(int i=0;i<A.size();i++) { for(int j=0;j<A[0].size();j++) { S += A[i][j]; } } return S; } // 测试 int main() { vector<vector<double>> A{{1,2,3},{4,5,6},{7,8,9}}; vector<vector<double>> L,U; lu_decomposition(A,L,U); double S = matrix_sum(A); cout << "A=" << endl; for(auto row:A) { for(auto ele:row) { cout << ele << " "; } cout << endl; } cout << "L=" << endl; for(auto row:L) { for(auto ele:row) { cout << ele << " "; } cout << endl; } cout << "U=" << endl; for(auto row:U) { for(auto ele:row) { cout << ele << " "; } cout << endl; } cout << "sum(A)=" << S << endl; return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值