There is an error in line 3. I can't figure out what the error is. Please help me find out.

6 views (last 30 days)
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.
  4 Comments
Walter Roberson
Walter Roberson on 4 Aug 2021

Using end to close a function is not always required.

You must use end for the following cases:

  • some other function in the file uses end matching its function declaration
  • you are using nested functions
  • you are creating a method of a classdef
  • you are defining a function inside a script
  • you want the semantics of creating a static workspace (which can be more efficient)

In the case of a single function that is the only function in it file with no script before it, then you only need the end if you want static workspace.

Using end is generally a good idea (though it can complicate debugging), but in the context of the posted user code, it is not required.

Sign in to comment.

Answers (2)

KSSV
KSSV on 4 Aug 2021
A = [ 1 2 3
4 5 6
7 8 9] ;
B = triu(A)
B = 3×3
1 2 3 0 5 6 0 0 9
iwant = sum(B(:))
iwant = 26
  1 Comment
KSSV
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
summa = 26
If you are getting any specific error. Show us the error here.

Sign in to comment.


Walter Roberson
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.

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!