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?
views:
70answers:
3Some 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.
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).
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