What are the ways to sum matrix elements in MATLAB?

前端 未结 6 2053
天涯浪人
天涯浪人 2021-02-08 01:26

Given the matrix:

A = [1 2 3; 4 5 6; 7 8 9];
  1. How could you use a for loop to compute the sum of the elements in the matrix?
  2. Writ
6条回答
  •  无人及你
    2021-02-08 01:49

    1)

    total = 0;
    for i=1:size(A,1)
      for j=1:size(A,2)
        total = total + A(i,j);
      end
    end
    

    2)

    total = sum(A(:));
    

提交回复
热议问题