How to do it?

5 ビュー (過去 30 日間)
SAYANTAN BHANJA
SAYANTAN BHANJA 2017 年 7 月 11 日
コメント済み: RAMAKANT SHAKYA 2019 年 2 月 8 日
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 corner, up and to the right) and elements that are to the right of it. For example, if the input is [1 2; 3 4; 5 6; 7 8], then the function would return 21.
  8 件のコメント
SAYANTAN BHANJA
SAYANTAN BHANJA 2017 年 7 月 16 日
function [N,r,c]=halfsum(x)
[r,c]=size(x);
if(r>c)
col_size=size(x,1);
zero_row=zeros(col_size,(r-c));
H=[x,zero_row];
s=flipud(H);
d=triu(s);
N=sum(d(:));
end
if(c>r)
col_size=size(x,2);
zero_row=zeros((c-r),col_size);
H=[zero_row;x];
s=flipud(H);
d=triu(s);
N=sum(d(:));
end
if(r==c)
s=flipud(x);
d=triu(s);
N=sum(d(:));
end
end
THANKS A LOT SIR GOT THIS ONE.........THANKS A LOT
Jorge Briceño
Jorge Briceño 2018 年 2 月 3 日
Hi everyone,
I solved the problem in two ways.
First one, using two for loops.
function [counter] = halfsum (A)
% ii = rows ; jj = columns
[m,n]=size(A);
counter = 0;
col=1;
for ii=m:-1:1
for jj=col:n
counter=counter + A(ii,jj);
end
col=col+1; % This line will add a number to your column value,
% so you will not start in the first column again.
end
counter;
end
Second one, using a for loop and an if statement.
function [counter] = halfsum (A)
% ii = rows ; jj = columns
[m,n]=size(A);
counter = 0;
ii=m;
for jj=1:n
if ii>0 % This contidion is mandatory, otherwise the ii could be equal zero, which will result in an error
counter=counter + sum(A(ii,jj:n)); % Function sum(A(ii,jj:n)) sums all the column in a row.
ii=ii-1; % This is equivalent to a row for loop.
end
end
counter;
end
I hope it helps.
Cheers!

サインインしてコメントする。

回答 (3 件)

Image Analyst
Image Analyst 2017 年 7 月 11 日
Hints. Look at functions size() (to get the size of the matrix), and sum(), tril(), triu(), flipud(), and/or flidlr(). Or simply use a nested for loop for a brute force method.

Srishti Saha
Srishti Saha 2018 年 4 月 7 日
This code works perfectly for me:
%function to compute sum of lower most right side triangle in an X*2 matrix
function u = halfsum(P)
u1 = P(end:-1:1, 1:end);
u2 = triu(u1);
u = sum(u2(:));
end

RAMAKANT SHAKYA
RAMAKANT SHAKYA 2019 年 2 月 7 日
編集済み: RAMAKANT SHAKYA 2019 年 2 月 8 日
function s=halfsum(a)
[m,n]=size(a);
s=0;
a=flip(a);
for r=1:m
for c=n:-1:r
s=s+a(r,c);
end
end
end
  2 件のコメント
Image Analyst
Image Analyst 2019 年 2 月 8 日
Do not use the built-in function sum() as the name of your variable. Call it theSum or something other than sum.
RAMAKANT SHAKYA
RAMAKANT SHAKYA 2019 年 2 月 8 日
thank you sir for improving me.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by