Search Program on this blog

Wednesday 19 August 2015

Write a function called halfsum that takes as input an at most two-­‐dimensional matrix A and computes the sum of the elements of A that are in the diagonal or are to the right of it. The diagonal is defined as the set of those elements whose column and row indexes are the same. For example, if the input is [1 2 3; 4 5 6; 7 8 9], then the function would return 26.

function sum=halfsum(v)
%Input v is 2-D matrix
%Output sum is a value
%Example: v = [1 2 3;4 5 6;7 8 9]
%         sum = halfsum(v)
%         sum = 26
sum=0;
[m,n]=size(v);
for i=1:m
    for j=1:n
        if i<=j   %sum of elements with row index <= column index
            sum=sum+v(i,j);
        end
    end
end

3 comments: