📅  最后修改于: 2023-12-03 15:05:24.249000             🧑  作者: Mango
In Matlab, you may come across a situation where you need to sum the values of rows of a matrix. For example, you might have a matrix where each row represents a different experiment, and you want to find the total value of all experiments. This can be easily achieved using the built-in sum
function in Matlab.
The syntax for the sum
function in Matlab is as follows:
B = sum(A,dim)
where:
A
is the input matrix.dim
is the dimension along which the summation is performed. By default, dim
is set to 1, which means the summation is performed along the first dimension (i.e. the rows).B
is the output matrix with the sum of each row (or column).Suppose we have a matrix A
with 3 rows and 4 columns:
A = [1 2 3 4; 5 6 7 8; 9 10 11 12];
To find the sum of each row, we can simply call the sum
function with dim=2
:
B = sum(A,2);
The output B
is a column vector with the sum of each row:
B =
10
26
42
If we want to find the sum of each column instead, we can simply call the sum
function with dim=1
:
B = sum(A,1);
The output B
is a row vector with the sum of each column:
B =
15 18 21 24
The sum
function in Matlab is a powerful tool for summing the values of rows (or columns) of a matrix. It can be easily implemented with just a few lines of code, and can save you a lot of time and effort when working with matrices.