开发者

How do I compute the sum of a subset of elements in a matrix?

开发者 https://www.devze.com 2023-01-15 18:43 出处:网络
I want to calcul开发者_如何学JAVAate 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?If you have a matrix M, you can f

I want to calcul开发者_如何学JAVAate 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?


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


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号