필터 지우기
필터 지우기

Write a function called halfsum that takes as input an at most two-dimensional array A and computes the sum of the elements of A that are in the lower right triangular part of A, that is, elements in the counter-diagonal (going from the bottom left c

조회 수: 8 (최근 30일)
function [sume] = halfsum(A)
[row,col] = size(A);
for c = 1 : 3
for i = row : -1 :1
for j = col : -1 : 1
sume = sum(A(i,j));
end
end
end
end
  댓글 수: 1
Emma Sellers
Emma Sellers 2019년 1월 4일
Can someone explain to me why this doesn't work?
It gives me the sum of the triangle that is in the top right instead of bottom left even though i feel like I have it iindexed to start at the end of the array and work backwards 3 times?

댓글을 달려면 로그인하십시오.

답변 (3개)

Yachika Singh
Yachika Singh 2020년 6월 1일
%for any random matrix
function summa=halfsum(A)
[row, col]=size(A);
summa=0;
for i=1:row
for j=i:col
if i<=j
summa=summa+(A(i,j));
end
end
end
end

Matt J
Matt J 2019년 1월 4일
편집: Matt J 2019년 1월 4일
The code you've shown will return only the value A(1,1), e.g.,
A =
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
[row,col] = size(A);
for c = 1 : 3
for i = row : -1 :1
for j = col : -1 : 1
sume = sum(A(i,j));
end
end
end
>> sume
sume =
1
because sume gets overwritten with every pass through the loops and sum(A(i,j)) is the same as A(i,j).

Manoj Kumar Sharma
Manoj Kumar Sharma 2020년 5월 15일
function [summa] = halfsum(A)
[row, col] = size(A);
for n=1:row
for i=n:col
summ(n,i)=(A(n,i));
end
end
summa=sum(summ,'all');
end

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by