Matlab 的求和函数 sum 是什么|Matlab 的求和函数 sum 如何使用
Matlab的求和函数sum的使用方法:1、使用“S = sum(A)”方式求和;2、使用“S = sum(A,dim)”方式按照指定维度求和;3、使用“S = sum(___,outtype)”方式指定输出结果的数据类型。
本文操作环境:Windows7系统,Matlab R2020a版本,Dell G3电脑。
Matlab的求和函数sum的使用方法:
1、S = sum(A),求和
如果x是一个向量,则计算向量的元素之和,如:
>> x = randi(10,1,10)x = 7 1 9 10 7 8 8 4 7 2>> sum(x)ans = 63
如果x的数组,则是计算数组的列之和,如:
>> x = pascal(4,2)x = -1 -1 -1 -1 3 2 1 0 -3 -1 0 0 1 0 0 0>> sum(x)ans = 0 0 0 -1
2、S = sum(A,dim),按照指定维度求和
dim = 1,表示对列求和
dim = 2,表示对行求和
dim = 3,表示对页求和
....,依次类推
例如:
>> a = toeplitz(1:5)a = 1 2 3 4 5 2 1 2 3 4 3 2 1 2 3 4 3 2 1 2 5 4 3 2 1>> sum(a,1)ans = 15 12 11 12 15>> sum(a,2)ans = 15 12 11 12 15
3、S = sum(___,outtype)指定输出结果的数据类型
可选字符串参数为'double','default'和'native'
一般来说,默认是'default'
有时候我们对整数求和,想要结果输出为double类型,就可以用这个参数
比如:
>> a = single(1:4)a = 1 2 3 4>> class(sum(a,'double'))ans =double>> class(sum(a))ans =single
Matlab的数据类型虽然比较全面,但是数据类型转化和其他语言不是完全一致,因此用的时候需要小心处理
4、S = sum(___,nanflag)是否忽略NaN值
有时候在求和的时候,数据中有NaN值影响,导致计算结果出现NaN,一般的处理方式是用isnan函数排除nan值,有了这个选项,就简单了
如:
>> a = rand(1,6);a(randperm(6,2)) = NaNa = 0.7060 0.0318
app制作教程: https://pan.baidu.com/s/108-QUBH8qA-g4FbFseep8g?pwd=rhwi 提取码: rhwi
微信小程序开发视频教程:https://pan.baidu.com/s/1wKG4e458GTdIhpgVY1WviQ?pwd=nuyq 提取码: nuyq
微信开发教程:https://pan.baidu.com/s/1ohpOQJ-qWPVCUVIjoY2JFA?pwd=tinh 提取码: tinh