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

6 次查看(过去 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