フィルターのクリア

how to get sum of elements of lower right triangular matrix.? i have tried this one, can anyone please correct this one

4 ビュー (過去 30 日間)
function [sum] = halfsum( a )
[m, n]=size(a); sum=0;
for i= m:-1:1
for j=n:-1:1
if i==j || j<=i
sum=sum+a(i,j);
end
end
end
end
output: halfsum([1 2 3;4 5 6;7 8 9])
ans =
34

採用された回答

Andrei Bobrov
Andrei Bobrov 2016 年 12 月 2 日
out = sum(a(rot90(tril(ones(size(a))),1)>0));

その他の回答 (2 件)

Image Analyst
Image Analyst 2016 年 12 月 2 日
Don't use sum() as the name of your variable! You're destroying a built-in function. I wish we could make this a sticky on the forum because it happens so often, probably more often than people confusing (row,column) with (x,y).
Use tril and fliplr like this:
m = magic(9) % Sample matrix.
lowerRight = fliplr(tril(fliplr(m)))
theSum = sum(lowerRight(:))
  2 件のコメント
vamshidhar Reddy Peruvala
vamshidhar Reddy Peruvala 2016 年 12 月 4 日
編集済み: vamshidhar Reddy Peruvala 2016 年 12 月 4 日
if possible can you please correct my code in "for loop" ..?
Image Analyst
Image Analyst 2016 年 12 月 4 日
The j loop should start at i, not n. And use theSum instead of sum. And the "if" is unnecessary.

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


Ibrahim Abouemira
Ibrahim Abouemira 2019 年 5 月 19 日
Hello,
Here's a proposed answer to your question.
The function takes as input at the most two-dimensional array. It computes the sum of the elements of that are in the lower right triangular part(counter-diagonal elements).
For example, if the input is [1 2; 3 4; 5 6; 7 8], then the function would return 21.

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by