What are the ways to sum matrix elements in MATLAB?

前端 未结 6 2057
天涯浪人
天涯浪人 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 02:07

    Avoid for loops whenever possible.

    sum(A(:))
    

    is great however if you have some logical indexing going on you can't use the (:) but you can write

    % Sum all elements under 45 in the matrix
    sum ( sum ( A *. ( A < 45 ) )
    

    Since sum sums the columns and sums the row vector that was created by the first sum. Note that this only works if the matrix is 2-dim.

提交回复
热议问题