What are the ways to sum matrix elements in MATLAB?

前端 未结 6 2054
天涯浪人
天涯浪人 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:47

    For very large matrices using sum(sum(A)) can be faster than sum(A(:)):

    >> A = rand(20000);
    >> tic; B=sum(A(:)); toc; tic; C=sum(sum(A)); toc
    Elapsed time is 0.407980 seconds.
    Elapsed time is 0.322624 seconds.
    

提交回复
热议问题