如何计算矩阵中元素子集的总和?

发布于 2024-09-19 16:00:30 字数 46 浏览 6 评论 0 原文

我想计算矩阵中可被 2 整除的元素的总和。我该怎么做?如何以坐标形式输出答案?

I want to calculate the sum of the elements in a matrix that are divisible by 2. How do I do it? And how do I output the answer in a co-ordinate form?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

私野 2024-09-26 16:00:30

如果您有一个矩阵 M,您可以找到一个 使用 (即掩码) rel="nofollow noreferrer">MOD 函数,无需循环即可对整个矩阵进行操作。对于矩阵中的偶数项,除以 2 后余数将为 0:

index = (mod(M,2) == 0);

您可以使用函数 FIND

[rowIndices,colIndices] = find(index);

通过使用上面的逻辑掩码索引 M 来提取偶数元素的总和,即可获得偶数元素的总和甚至条目并使用 SUM 函数将它们相加:

evenSum = sum(M(index));

这是一个使用函数 MAGIC< 创建矩阵 M 的示例/a>:

>> M = magic(3)

M =

     8     1     6
     3     5     7
     4     9     2

>> index = (mod(M,2) == 0)

index =

     1     0     1     %# A matrix the same size as M with
     0     0     0     %#   1 (i.e. "true") where entries of M are even
     1     0     1     %#   and 0 (i.e. "false") elsewhere

>> evenSum = sum(M(index))

evenSum =

    20

If you have a matrix M, you can find a logical index (i.e. mask) for where the even elements are by using the MOD function, which can operate on an entire matrix without needing loops. For entries in the matrix that are even the remainder will be 0 after dividing by 2:

index = (mod(M,2) == 0);

You can get the row and column indices of these even entries using the function FIND:

[rowIndices,colIndices] = find(index);

And you can get the sum of the even elements by indexing M with the logical mask from above to extract the even entries and using the SUM function to add them up:

evenSum = sum(M(index));

Here's an example with a matrix M created using the function MAGIC:

>> M = magic(3)

M =

     8     1     6
     3     5     7
     4     9     2

>> index = (mod(M,2) == 0)

index =

     1     0     1     %# A matrix the same size as M with
     0     0     0     %#   1 (i.e. "true") where entries of M are even
     1     0     1     %#   and 0 (i.e. "false") elsewhere

>> evenSum = sum(M(index))

evenSum =

    20
我们只是彼此的过ke 2024-09-26 16:00:30

这是仅包含偶数值的矩阵 M

(mod(M,2) == 0).*M

您可以使用 sum(M )sum(sum(M)) (不确定“坐标形式”是什么意思)。

This is the matrix M with only its even values:

(mod(M,2) == 0).*M

You can sum it with sum(M) or sum(sum(M)) (not sure what "co-ordinate form" means).

长梦不多时 2024-09-26 16:00:30

一些伪代码。几乎循环遍历每一行的每一列。

sum = 0
for(i = 0; i < matrix.num_rows; i++) {
  for(j = 0; j < matrix.num_cols; j++) {
    if(matrix[i][j] % 2 == 0)
      sum += matrix[i][j]
  }
}

但不确定坐标形式是什么意思。

Some pseudo-code. Pretty much loop through each column for each of the rows.

sum = 0
for(i = 0; i < matrix.num_rows; i++) {
  for(j = 0; j < matrix.num_cols; j++) {
    if(matrix[i][j] % 2 == 0)
      sum += matrix[i][j]
  }
}

Not sure what you mean by Coordinate form though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文