Write a function called sum_half that takes as input a square matrix A and computes the sum of its elements that are in the upper right triangular part of A, that is, elements in the diagonal and elements that are to the right of it. For example, if the input is [1 2 3; 4 5 6; 7 8 9], then the function would return 26. (That is, 1+2+3+5+6+9) Note, the function triu is not allowed. Please write as you would in MATLAB
function [sum] = sum_half (A)
sum = 0;
% if i <= j i.e, above the diagonal matrix
for i=1:length(A)
for j = 1:length(A(i,:))
if i <=j
% calculating sum of
% upper trianglar matrix
sum = sum + A(i,j);
end
end
end
% returning sum
sum;
end
Code
Output
Get Answers For Free
Most questions answered within 1 hours.