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

1 view (last 30 days)
Swetha Balaji Rao
Swetha Balaji Rao on 4 Aug 2021
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;
functionsumma = halfsum(A)
[x, y] = size(A);
ifx = = y
summa = 0;
forn = 1:y
summa = summa + sum(A(n, n:y));
end
elseifx ~ = y
ifx > y
summa = 0;
forn = 1:y
summa = summa + sum(A(n, n:y));
end
elseifx < y
summa = 0;
forn = 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

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
给定的函数也没有error. It works fine.
A = [1 2 3
4 5 6
7 8 9] ;
[x, y] = size(A);
ifx = = y
summa = 0;
forn = 1:y
summa = summa + sum(A(n, n:y));
end
elseifx ~ = y
ifx > y
summa = 0;
forn = 1:y
summa = summa + sum(A(n, n:y));
end
elseifx < y
summa = 0;
forn = 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.

s manbetx 845


Release

R2021a

Community Treasure Hunt

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

Start Hunting!