Write a function that returns triangular part of matrix using loops
7 次查看(过去 30 天)
显示 更早的评论
I just started to learn how to program using matlab and in class we have covered if and for loops but I am really not sure how to solve this problem. Can someone please help?
Write a function that inputs a square matrix and returns
another matrix which is identical to the first, except that the elements below the diagonal are
set to zero.
Your function should use nested for loops. If given a matrix:
4 3 4 4
4 1 4 2
1 2 1 4
4 3 4 1
It should return the following matrix:
4 3 4 4
0 1 4 2
0 0 1 4
0 0 0 1
Show your output for an illustrative 5x5 matrix input.
1 个评论
回答(2 个)
Friday N. Abolorunke
2020-6-8
编辑:Friday N. Abolorunke
2020-6-8
function summa = halfsum(A)
[m,n] = size(A);
for ii = 1:m
for jj = 1:n
if ii > jj
A(ii,jj) = 0
summa = sum(A(:));
elseif ii == 1
summa = sum(A);
end
end
end
end
For a 3 x 3 matrix. you'll want to assign zero to A(2,1),A(3,1) and A(3,2). Notice that the index of the elements in the row most always be greater than that of the col
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!