MATLAB中矩阵元素求和的方法有哪些? [英] What are the ways to sum matrix elements in MATLAB?

查看:37
本文介绍了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天全站免登陆