3 views (last 30 days)

Show older comments

Write a function called halfsum that takes as input a matrix and computes the sum of the elements in the diagonal and are to the right of it. The diagonal is defined as the set of those elements whose column and row indexes are the same. In other words, the function adds up to the element in the upper triangular part of the matrix. The name of the output argument is summa.

For example,

A =

1 2 3

4 5 6

7 8 9

The function would return 26 (1 + 5 + 9 + 2 + 3 + 6 = 26)

This is my code for the function;

function summa = halfsum(A)

[x, y] = size(A);

if x == y

summa = 0;

for n = 1:y

summa = summa + sum(A(n, n:y));

end

elseif x ~= y

if x > y

summa = 0;

for n = 1:y

summa = summa + sum(A(n, n:y));

end

elseif x < y

summa = 0;

for n = 1:x

summa = summa + sum(A(n, n:y));

end

end

end

When I was debugging, MATLAB showed error in line 3. My code works fine but I don't know what's the error in line 3.

KSSV
on 4 Aug 2021

A = [ 1 2 3

4 5 6

7 8 9] ;

B = triu(A)

iwant = sum(B(:))

KSSV
on 4 Aug 2021

The given function too has no error. It works fine.

A = [1 2 3

4 5 6

7 8 9] ;

[x, y] = size(A);

if x == y

summa = 0;

for n = 1:y

summa = summa + sum(A(n, n:y));

end

elseif x ~= y

if x > y

summa = 0;

for n = 1:y

summa = summa + sum(A(n, n:y));

end

elseif x < y

summa = 0;

for n = 1:x

summa = summa + sum(A(n, n:y));

end

end

end

summa

If you are getting any specific error. Show us the error here.

Walter Roberson
on 4 Aug 2021

You tried to run the function without passing any matrix to it, and matlab complained that it could not find any input being passed to it.

When a function requires parameters then you cannot just press the green Run button, and you cannot just give the name of the function by itself to run the function.

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!