在MATLAB中求和矩阵元素的方法是什么? [英] What are the ways to sum matrix elements in MATLAB?

查看:197
本文介绍了在MATLAB中求和矩阵元素的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出矩阵:

A = [1 2 3; 4 5 6; 7 8 9];

  1. 如何使用for循环计算矩阵中元素的总和?
  2. 使用函数sum编写一行MATLAB命令以求和 A中的矩阵元素.
  1. How could you use a for loop to compute the sum of the elements in the matrix?
  2. Write a one line MATLAB command using the function sum to sum the matrix elements in A.

我的答案:

1)

for j=1:3,
    for i=j:3,
        A(i,:) = A(i,:)+A(j+1,:)+A(j+2,:)
    end
end

2)

sum(A)

这些是正确答案吗?我不知道如何使用ifwhilefor.有人可以向我解释吗?

Are these the correct answers? I didn't know how to use if, while and for. Can anyone explain it to me?

推荐答案

对于使用sum(sum(A))的超大型矩阵,其速度可能比sum(A(:))快:

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.

这篇关于在MATLAB中求和矩阵元素的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆