octave sum all elements in matrix
To sum all the elements in a matrix in the C programming language, you can use the following code:
#include <stdio.h>
#define ROWS 3
#define COLS 3
int main() {
int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum = 0;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
sum += matrix[i][j];
}
}
printf("Sum of all elements in the matrix: %d\n", sum);
return 0;
}
In this code, we first define the dimensions of the matrix using the ROWS
and COLS
constants. Then, we declare a 2D array called matrix
and initialize it with some values.
Next, we declare a variable sum
and initialize it to 0. We use two nested for
loops to iterate over each element in the matrix. The outer loop iterates over the rows, and the inner loop iterates over the columns. We access each element using the matrix[i][j]
syntax and add it to the sum
variable.
Finally, we print out the value of sum
, which represents the sum of all the elements in the matrix.
I hope this code snippet helps! Let me know if you have any further questions.