MATLAB---sum函數用法
1/ SUM Sum of elements.
S = SUM(X) is the sum of the elements of the vector X. If
X is a matrix, S is a row vector with the sum over each
column. For N-D arrays, SUM(X) operates along the first
non-singleton dimension.
If X is floating point, that is double or single, S is
accumulated natively, that is in the same class as X,
and S has the same class as X. If X is not floating point,
S is accumulated in double and S has class double.
S = SUM(X,DIM) sums along the dimension DIM.
S = SUM(X,'double') and S = SUM(X,DIM,'double') accumulate
S in double and S has class double, even if X is single.
S = SUM(X,'native') and S = SUM(X,DIM,'native') accumulate
S natively and S has the same class as X.
Examples:
If X = [0 1 2
3 4 5]
then sum(X,1) is [3 5 7] and sum(X,2) is [ 3
12];
If X = int8(1:20) then sum(X) accumulates in double and the
result is double(210) while sum(X,'native') accumulates in
int8, but overflows and saturates to int8(127).
2/
文法
B=sum(A)
B=sum(A,dim)
函數描述
B=sum(A)
返回數組中各個不同空間維的數值和,若A為一個向量,sum(A)將A返迴向量元素和。若A為一個矩陣,sum(A)將A中列向量作為基向量,返回每一列基向量各元素和的行向量。若A為一個多維陣列,sum(A)將沿第一個非單位的資料作為向量,返回一個行向量數組。
B=sum(A,dim)
沿由標量dim指定的維對矩陣A的元素求和。
3/
>> A
A =
3 4 2
1 5 3
4 7 1
>> sum(A)
ans =
8 16 6
>> sum(A,2)
ans =
9
9
12
>> sum(A,1)
ans =
8 16 6
>> A(:,2)
ans =
4
5
7