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

3 visualizzazioni (ultimi 30 giorni)
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 Commento
Emma Sellers
Emma Sellers il 4 Gen 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?

Accedi per commentare.

Risposte (3)

Yachika Singh
Yachika Singh il 1 Giu 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 il 4 Gen 2019
Modificato: Matt J il 4 Gen 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 il 15 Mag 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

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by