tags:

views:

70

answers:

3

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 ans in a co-ordinate form?

A: 

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.

Aaron Hathaway
OP tagged MATLAB as the language. Loops should be avoided, since vectorization is usually much faster. Gnovice's solution can even be pared down to one line: `sum(M(mod(M,2)==0))`
Doresoom
Oh wow, thanks. I guess I didn't realize that the OP originally tagged it as MATLAB. My mistake.
Aaron Hathaway
+1  A: 

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

adamk
MATLAB doesn't have a `%` operator. You want [MOD](http://www.mathworks.com/help/techdoc/ref/mod.html). `%` is for making comments.
gnovice
@gnovice - thanks, that's what you get for typing too fast :)
adamk
@adamk: No problem. That's an easy one to forget after having worked with many other languages that do have `%` as an operator.
gnovice
+3  A: 

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
gnovice

related questions