Filter löschen
Filter löschen

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 Ansichten (letzte 30 Tage)
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 Kommentar
Emma Sellers
Emma Sellers am 4 Jan. 2019
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?

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Yachika Singh
Yachika Singh am 1 Jun. 2020
%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 am 4 Jan. 2019
Bearbeitet: Matt J am 4 Jan. 2019
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 am 15 Mai 2020
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

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by